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

huangapple go评论91阅读模式
英文:

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    
}

huangapple
  • 本文由 发表于 2015年6月7日 03:58:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/30687000.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定