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

Golang Decode Nested JSON into Nested Struct

让我们看一下下面的代码片段:

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:}}

问题:

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

NestembeddedInput.

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    
}