donglian1982 2018-02-10 00:52
浏览 99
已采纳

golang json解码并带有字段名

For following JSON

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

how can i map it into golang struct, normally, the structure will be

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

as the json field name is the attribute of struct, thank you in advance.

  • 写回答

1条回答 默认 最新

  • dongluojiao6322 2018-02-10 01:47
    关注

    You have to use custom JSON marshalling

    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
    ", person.Name, person.Age)
            }
        }
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持