VisualBean
VisualBean

Reputation: 5008

unmarshall anonymous json field to "named" field

Say I have the following json

{
    "unknown": {
        "knownArray": [
            {"property": "somevalue", "otherproperty": false}
        ],
        "otherKnownArray": [""]
    }
}

And I have the following structs to represent this data

type Model struct {
    ObjectName string
    KnownArray []KnownType `json:"knownArray"`
    OtherKnownArray []string `json:"otherKnownArray"`
}

type KnownType struct {
    Property string `json:"property1"`
    Otherproperty bool   `json:"otherproperty"`
}

doing

var model Model

json.Unmarshal(content, &model)

Does not deserialize any of the json unfortunately.

How do I deserialize to my Model correctly?
How do I deserialize the json so that ObjectName = "unknown"?

Im not quite understanding the internals of encoding/json when it comes to anonymous json fields.

Ive also tried wrapping Model in a third "outer" Model, but still does not work with the anonymous json field.

Upvotes: 0

Views: 287

Answers (1)

Pan Ke
Pan Ke

Reputation: 579

can use map[string]Model to encode. https://play.golang.org/p/QWXQZFjBgRB

package main

import (
    "fmt"
    "encoding/json"
)

type Model struct {
    ObjectName string
    KnownArray []KnownType `json:"knownArray"`
    OtherKnownArray []string `json:"otherKnownArray"`
}

type KnownType struct {
    Property string `json:"property"`
    Otherproperty bool   `json:"otherproperty"`
}

func main() {
        jsonstring := `{
            "unknown": {
                "knownArray": [
                        {"property": "somevalue", "otherproperty": false}
                ],
                "otherKnownArray": [""]
            }
    }`
    a := make(map[string]Model)
    json.Unmarshal([]byte(jsonstring), &a)
    var m Model
    for k, v := range(a) {
        m = v
        m.ObjectName = k
        break
    }
    fmt.Println(m.ObjectName, m.KnownArray, m.OtherKnownArray)
}

Upvotes: 2

Related Questions