duande3134 2015-06-06 19:58
浏览 68
已采纳

Golang将嵌套的JSON解码为嵌套的结构

Lets look at the following code snippet:

type Input struct {
    Value1   string
    Value2   string
    Value3   string
    Value4   string
    Nest         
}

type Nest struct {
    ID  string
}
input := &Input{}
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(&input); err != nil {
    fmt.Printf("something went wrong %v", err)
}
fmt.Printf("Json Input = %+v
", input)

I'm sending the following via cURL:

curl -k -vvv  -X POST -d '{"value1":"test", "value2":"Somevalue", "value3":"othervalue", "Nest":{"ID": "12345"}}' http://localhost:8000/endpoint

.. and get the following output:

{Value1:test Value2:Somevalue Value3:othervalue Value4: Nest:{ID:}}

Problem:

I'm not getting a good decoding of the nested struct for some reason. Moreover, I'm not really sure if it's my code or the way I'm calling it.

  • 写回答

1条回答 默认 最新

  • dsdapobp26141 2015-06-06 20:39
    关注

    Nest is embedded in Input.

    The JSON {"value1":"test", "value2":"Somevalue", "value3":"othervalue", "ID": "12345"} will be correctly marshalled into your Input.

    If you want to use the JSON body from your Question then you will have to change Input to the following

    type Input struct {
        Value1   string
        Value2   string
        Value3   string
        Value4   string
        Nest     Nest    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度