英文:
Unmarshalling a json array in golang
问题
我对golang的解组(unmarshalling)有一个问题。我试图解组Json数组,但在一个解码中它返回nil结果,而在另一个解码中却成功了。我不明白其中的原因。这是代码中的错误还是预期的行为?
package main
import "fmt"
import "encoding/json"
type PublicKey struct {
Id int
Key string
}
type KeysResponse struct {
Collection []PublicKey
}
func main() {
keysBody := []byte(`[{"id": 1,"key": "-"},{"id": 2,"key": "-"},{"id": 3,"key": "-"}]`)
keys := make([]PublicKey, 0)
json.Unmarshal(keysBody, &keys) // 这个可以工作
fmt.Printf("%#v\n", keys)
response := KeysResponse{}
json.Unmarshal(keysBody, &response) // 这个不工作
fmt.Printf("%#v\n", response)
}
你可以在这里查看代码:http://play.golang.org/p/L9xDG26M8-
英文:
I have a question regarding the golang unmarshalling . I was trying to unmarshal Json array but it is giving nil result for one decoding while it is successful in the other. I don't understand the reason behind it. Is it a mistake in the code or expected?
package main
import "fmt"
import "encoding/json"
type PublicKey struct {
Id int
Key string
}
type KeysResponse struct {
Collection []PublicKey
}
func main() {
keysBody := []byte(`[{"id": 1,"key": "-"},{"id": 2,"key": "-"},{"id": 3,"key": "-"}]`)
keys := make([]PublicKey,0)
json.Unmarshal(keysBody, &keys)//This works
fmt.Printf("%#v\n", keys)
response := KeysResponse{}
json.Unmarshal(keysBody, &response)//This doesn't work
fmt.Printf("%#v\n", response)
}
答案1
得分: 2
这不太可能有效。在JSON中,你有一个类型为PublicKey
的数组。KeysResponse
类型应该用于以下形式的JSON:
{
"Collection": [{"id": 1,"key": "-"},{"id": 2,"key": "-"},{"id": 3,"key": "-"}]
}
这与你的情况不符。如果你想将数据存储在该类型中,我建议在解析为keys
之后的那一行使用response := KeysResponse{keys}
。
为了详细说明这个区别,在正常工作的情况下,JSON只是一个包含对象的数组。我上面写的JSON是一个对象,它有一个名为Collection
的属性,该属性是一个数组类型,数组中的对象由PublicKey
类型表示(具有名为id的整数和名为key的字符串)。在处理解析JSON的代码时,用这种简单的英语描述结构是很有帮助的,它能准确告诉你在Go中需要哪些类型/结构来保存数据。
英文:
That's not expected to work. What you have in the json is an array of type PublicKey
. The KeysResponse
type would be used for json looking like this;
{
"Collection": [{"id": 1,"key": "-"},{"id": 2,"key": "-"},{"id": 3,"key": "-"}]
}
Which is not what you have. If you want the data to be stored in that type I'd recommend the following; response := KeysResponse{keys}
on the line after you unmarshal into keys
.
To elaborate on that distinction. In the working case the json is just an array with objects inside of it. The json I wrote above is an object which has a single property named Collection
which is of type array and the objects in the array are represented by the PublicKey
type (objects with an int called id and a string called key). When working on code to unmarshal json, it's helpful to describe the structure using plain English like this, it tells you precisely what types/structures you need in Go to hold the data.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论