Home > Software design >  JSON Decoder cannot decode an object into an object
JSON Decoder cannot decode an object into an object

Time:12-01

type MiddleMan struct {
    User CompletedByUser `json:"user"`
}
type CompletedByUser struct {
    DisplayName string `json:"displayName"`
    Id          string `json:"id"`
}

Using the following types, I run the code

shorterJsonString := `{
    "user":{
        "displayName":null,
        "id":"a03dfee5-a754-4eb9"
    }
 }`

if !json.Valid([]byte(shorterJsonString)) {
    log.Println("Not valid")
}
var middleMan models.MiddleMan

newReader := strings.NewReader(shorterJsonString)
json.NewDecoder(newReader).Decode(&middleMan)

log.Println(middleMan)

Unfortunately, the decoder is seemingly broken for nested objects. Rather than spitting out actual objects, the print prints out

{{ a03dfee5-a754-4eb9 }}

It seems to flatten the whole thing into the id field. What is going on here?

CodePudding user response:

What did you expect to happen / get printed?

The log package (which uses the fmt package) prints structs enclosed in braces, listing field values separated by spaces.

Your MiddleMan has a single field, so it'll look like this:

{field}

Where field is another struct of type CompletedByUser, which has 2 fields, so it'll look like this:

{{field1 field2}}

Where field is of string type, being the empty string, so you'll see the value of field2 prefixed with a space:

{{ a03dfee5-a754-4eb9}}

If you print it adding field names:

log.Printf("% v", middleMan)

You'll see an output like:

{User:{DisplayName: Id:a03dfee5-a754-4eb9}}

Using another (Go-syntax) format:

log.Printf("%#v", middleMan)

Output:

main.MiddleMan{User:main.CompletedByUser{DisplayName:"", Id:"a03dfee5-a754-4eb9"}}

Try this on the Go Playground.

  • Related