donglisi8644 2018-04-10 05:53
浏览 78
已采纳

如何在Golang中不解组嵌套的JSON

I have some JSON that I wish to unmarshal in Go. One of the top-level keys of the JSON dictionary has a value that is also parsable JSON. For example:

{ 
    "Name": "Tony",
    "Age": 50,
    "Extra": {\"Weight\":180}
}

I have a corresponding struct that I want to unmarsal to:

type Person struct {
    Name string
    Age int
    Extra []byte
 }

I want the Extra key to be a byte array because the JSON structure will vary and the structure of it is not important to the program being written. The program simply needs to push this data along down the line as a byte array.

How can I coax the Go JSON encoder to handle the value of extra like this?

  • 写回答

2条回答 默认 最新

  • douzhuan1467 2018-04-10 06:07
    关注

    You have two options:

    Using json.RawMessage

    Here you have to slightly change your struct:

    type Person struct {
        Name string
        Age int
        Extra *json.RawMessage
    }
    

    then, you can Unmarshal as usual

    person := Person{}
    err := json.Unmarshal(raw_bytes, &person)
    // handle err
    

    finally, you can Unmarshal Extra again, you can even do some assertion type on it to previously detect the type

    var extra_option_1 string
    extra_option_2 := AnotherStruct{}
    
    err := json.Unmarshal(raw_bytes, &extra_option_1)
    // handle err
    
    // or
    
    err := json.Unmarshal(raw_bytes, &extra_option_2)
    // handle err
    

     Using map[string]interface{}{} - honestly not so useful in your case

    You can directly unmarshal "unknown" or dynamics payloads using a general map[string]interface{}{}.
    BUT I discourage this usage because is slower and you should always know what to expect.

    Anyway, hereafter is a pseudo code:

    payload := map[string]interface{}{}
    err := json.Unmarshal(raw_bytes, &payload)
    // handle err
    

    In this last case, you need even to do assertion to each field.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?