英文:
Handling two forms of JSON?
问题
我正在使用Go编写一个应用程序,它将接收两种形式的JSON:
示例1:
{"book_data":{"title":"book-title","page_number":457}}
示例2:
{"book_data":{"collection":214},"books":{"data":[{"title":"book-title","page_number":457},{"title":"book-title","page_number":354}]}}
我认为我可以创建一个如下的结构体,并将JSON解组到其中:
type Book struct {
Title string `json:"title"`
PageNumber int `json:"page_number"`
}
但这只适用于第一个示例。
我该如何处理这两个示例的JSON?
英文:
I'm writing an application in Go that will recieve two forms of JSON:
Example 1:
{"book_data":{"title":"book-title","page_number":457}}
Example 2:
{"book_data":{"collection":214},"books":{"data":[{"title":"book-title","page_number":457},{"title":"book-title","page_number":354}]}}
I thought that I could create a struct like the following and unmarshal JSON into it:
type Book struct {
Title string `json:"title"`
PageNumber int `json:"page_number"`
}
but that only works for the first example.
How can I handle JSON from both examples?
答案1
得分: 2
你可以先部分地使用json.RawMessage
进行解组,然后根据解组后的有效载荷决定下一步操作。你也可以直接解组为更通用的结构。类似于:
type Book struct {
Title string `json:"title"`
PageNumber int `json:"page_number"`
}
type BookShelf struct {
BookData struct {
Book
Collection int `json:"collection"`
} `json:"book_data"`
Books struct {
Data []Book `json:"data"`
} `json:"books"`
}
对我来说,这看起来很易读、有意义,并且足够方便进行进一步处理。
英文:
You can first unmarshal partly in json.RawMessage
to next decide depending of unmarshalled payload. And you also can just unmarshal in more generic structure. Something like
type Book struct {
Title string `json:"title"`
PageNumber int `json:"page_number"`
}
type BookShelf struct {
BookData struct {
Book
Collection int `json:"collection"`
} `json:"book_data"`
Books struct {
Data []Book `json:"data"`
} `json:"books"`
}
which for me looks readable, meaningful and handy enough for further processing.
答案2
得分: 0
为什么不将其反序列化为map[string]interface{},然后使用结果来确定需要处理的表单?然后,您可以为每个表单使用特定的结构类型进行反序列化。
另一种方法是使用以下包来检查不同的属性,以便您可以决定在真正的反序列化过程中使用哪个结构。
https://github.com/go-xmlpath/xmlpath/tree/v2
英文:
Why not unmarshal to a map[string]interface{} and then use the result to see which form you need to handle? You can then deserialize with a specific struct type for each form.
Another way would be to use the following package to check for differing attributes, so you can decide which struct to use for the real unmarshaling.
答案3
得分: 0
你可以将JSON反序列化为map,因为你的键是字符串,值可以是任何类型,比如map[string]interface{}。如果你不确定数据类型或值,可以使用interface{},因为它可以存储任何值。然后使用result来查看它的形式,并将其反序列化为特定的结构体类型。
另一种将JSON转换为Go结构体的方法是使用这个工具。
https://mholt.github.io/json-to-go/
英文:
You can unmarshal to map because your key is string and value may be anything like - map[string]interface{}. If you are not sure any data type or value then use interface{} beacause it can store any value. Then use result to see which form it is, And deserialize to specific struct type.
Another way to convert JSON to go struct is use this tool.
https://mholt.github.io/json-to-go/
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论