doujiu8479
2019-03-23 22:02
浏览 176

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.

图片转代码服务由CSDN问答提供 功能建议

我的结构如下:

  type节点结构 {
名称字符串
子项[] * Node 
值[] string 
} 
   
 
 

我也有一组描述我的树的json文件,例如 如:

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

如何将这些文件反序列化为结构?

我发现的所有示例似乎都需要带有命名键/值对的不同结构。

为此,结构是键:

  • 键是结构名称
  • 映射内容是孩子
  • 列表内容是值

    我无法理解如何将此逻辑映射到golang json序列化程序中。

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duanhuang2804 2019-03-23 23: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.

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题