【问题标题】:Golang Decode Nested JSON into Nested StructGolang 将嵌套 JSON 解码为嵌套结构
【发布时间】:2015-06-06 19:58:15
【问题描述】:

让我们看看下面的代码sn-p:

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\n", input)

我通过 cURL 发送以下内容:

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

.. 并得到以下输出:

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

问题:

由于某种原因,我没有很好地解码嵌套结构。此外,我不确定这是我的代码还是我调用它的方式。

【问题讨论】:

    标签: json curl struct go nested


    【解决方案1】:

    NestInput 中是embedded

    JSON {"value1":"test", "value2":"Somevalue", "value3":"othervalue", "ID": "12345"} 将正确编组到您的 Input

    如果您想使用问题中的 JSON 正文,则必须将 Input 更改为以下内容

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

    【讨论】:

    • 奇怪,我以为我已经尝试过了。不过这次确实奏效了。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-29
    • 2021-12-24
    • 1970-01-01
    • 1970-01-01
    • 2017-05-11
    相关资源
    最近更新 更多