英文:
Golang Decode Nested JSON into Nested Struct
问题
让我们来看一下以下的代码片段:
type Input struct {
Value1 string
Value2 string
Value3 string
Value4 string
Nest 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:}}
问题:
由于某种原因,我无法正确解码嵌套结构。此外,我不确定是我的代码有问题还是我调用的方式有问题。
英文:
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\n", 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
得分: 4
Nest被嵌入在Input中。
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
}
英文:
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
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论