doujiu8479 2019-03-23 14:02
浏览 194
已采纳

Golang JSON序列化/反序列化

I have a struct as follows:

type Node struct {
    Name     string
    Children []*Node
    Values   []string
}

I also have a set of json files describing my trees such as:

{
  "something": {
    "someblah": [
      "fluf",
      "glah"
    ],
    "someother": {
      "someotter": [
        "blib",
        "fnar"
      ]
    }
  }
}

How can I deserialize these files into the structs?

All the examples I found seem to require a different structure with named key/value pairs.

For this, the structure is key:

  • the key is the struct name
  • the map contents are children
  • the lists contents are values

I cannot understand how to map this logic into the golang json serializer.

  • 写回答

1条回答 默认 最新

  • duanhuang2804 2019-03-23 15:04
    关注

    The easiest approach is to decode to map[string]interface{} and convert that to the desired structure:

    var m map[string]interface{}
    err := json.Unmarshal(data, &m)
    if err != nil {
        // handle error
    }
    node := convert(m, "")
    
    ...
    
    func convert(name string, m map[string]interface{}) *Node {
        n := Node{Name: name}
        for k, v := range m {
            switch v := v.(type) {
            case []interface{}:
                nn := Node{Name: k}
                for _, e := range v {
                    s, ok := e.(string)
                    if !ok {
                        panic(fmt.Sprintf("expected string, got %T", e))
                    }
                    nn.Values = append(nn.Values, s)
                }
                n.Children = append(n.Children, &nn)
            case map[string]interface{}:
                n.Children = append(n.Children, convert(k, v))
            default:
                panic("unexpected type")
            }
        }
        return &n
    }
    

    The convert function panics when it encounters a value of an unexpected type. Depending on the requirements of your application, you may want to ignore these values or return an error.

    Run it on the playground.

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

悬赏问题

  • ¥15 爱快路由器端口更改错误导致无法访问
  • ¥20 安装catkin时遇到了如下问题请问该如何解决呢
  • ¥15 VAE模型如何输出结果
  • ¥15 编译python程序为pyd文件报错:{"source code string cannot contain null bytes"
  • ¥20 关于#r语言#的问题:广义加行模型拟合曲线后如何求拐点
  • ¥15 fluent设置了自动保存后,会有几个时间点不保存
  • ¥20 激光照射到四象线探测器,通过液晶屏显示X、Y值
  • ¥15 这怎么做,怎么在我的思路下改下我这写的不对
  • ¥50 数据库开发问题求解答
  • ¥15 安装anaconda时报错
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部