json.Marshal(struct) returns empty JSON "{}": how to fix?
Hi everyone! I'm new to Go and encountered a strange problem when working with JSON. I have a struct, I fill it with data, try to serialize it to JSON using `json.Marshal()`, but the output only gives empty curly braces `{}`. Here's my code:
```go
package main
import (
"encoding/json"
"fmt"
)
type User struct {
Name string
Age int
}
func main() {
u := User{"Alice", 30}
result, err := json.Marshal(u)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println(string(result)) // Outputs: {}
}
```
I expected to see `{"Name":"Alice","Age":30}`, but I only see `{}`. There's no error, but the data is lost. What am I doing wrong? I checked that the struct is filled correctly — if I print the fields via `fmt.Println(u.Name, u.Age)`, they
No answers yet.
Log in to leave an answer