golang json解码字段名称

时间:2018-02-10 00:52:08

标签: json go decode

用于跟随JSON

{
    "Jon": {
       "Age": 15
    },
    "Mary": {
       "Age": 17
    } 
}

如何将其映射到golang结构中,通常,结构将是

type Person struct {
    Name string `json:??,string`
    Age int `json:Age, int`
}

因为json字段名是struct的属性,所以请提前感谢。

1 个答案:

答案 0 :(得分:3)

您必须使用自定义JSON编组

package main

    import (
        "encoding/json"
        "log"
        "fmt"
    )

    type Person struct {
        Name string `json:??,string`
        Age  int    `json:Age, int`
    }

    type People map[string]*Person

    func (p *People) UnmarshalJSON(data []byte) error {
        var transient = make(map[string]*Person)
        err := json.Unmarshal(data, &transient)
        if err != nil {
            return err
        }
        for k, v := range transient {
            v.Name = k
            (*p)[k] = v
        }
        return nil
    }

    func main() {

        jsonInput := `
        {
            "Jon": {
        "Age": 15
        },
            "Mary": {
        "Age": 17
        }
        }
    `

        var people People = make(map[string]*Person)

        err := people.UnmarshalJSON([]byte(jsonInput))
        if err != nil {
            log.Fatal(err)
        }

        for _, person := range people {
            fmt.Printf("%v -> %v\n", person.Name, person.Age)
        }
    }