GoLang Marshal to empty string

Advertisements

Would you help me understand why Marshal of the struct Person is empty but for the struct User is not ?

// You can edit this code!
// Click here and start typing.
package main

import (
    "encoding/json"
    "fmt"
)

type Person struct {
    name  string
    addr  string
    phone string
}

type User struct {
    Name        string
    Age         int
    Active      bool
    lastLoginAt string
}

func main() {

    p1 := Person{name: "joe", addr: "a. str", phone: "123"}
    u1 := User{Name: "Bob", Age: 10, Active: true, lastLoginAt: "today"}

    fmt.Println(p1)
    fmt.Println(u1)

    u, err := json.Marshal(u1)
    p, err := json.Marshal(p1)

    if err == nil {
        fmt.Println(string(p))
        fmt.Println(string(u))
    }
}
{joe a. str 123}
{Bob 10 true today}
{}
{"Name":"Bob","Age":10,"Active":true}

Program exited.

https://go.dev/play/p/C3-Baq6JI2s

>Solution :

In your Person struct your fields aren’t exported, which means it cannot be accessed outside of your package. In Go if a field start with an uppercase letter it’s exported else its unexported (like private in OOP). Change your struct definition and it will work.

But because in the JSON there are keys with lowercase letters, you should add json tags to your struct like:

type Person struct {
    Name  string `json:"name"`
    Addr  string `json:"addr"`
    Phone string `json:"phone"`
}

Leave a ReplyCancel reply