[英]How to unmarshall a json file with nested objects which can be different from eachother in Golang
使用看起來像這樣的 json 文件,其中某人只能擁有一個社交,但可能因人而異,我將如何將其解組為結構。
[
{
"name": "Bob",
"age": 14,
"occupation": "Builder",
"social": {
"facebook": "Bob_the_builder"
},
{
"name": "Alice",
"age": 14,
"occupation": "Builder",
"social": {
"twitter": "Alice_the_builder"
}
]
我當前的結構變量看起來像這樣。
type User struct {
Name String 'json:"name"'
Age int 'json:"age"'
Occupation String 'json:"occupation"'
Social Social 'json:"social"'
}
type Social struct {
Facebook String 'json:"facebook"'
Twitter String 'json:"twitter"'
}
這是解組 json 的正確方法,還是會因為“社交”結構需要兩個不同的字符串而失敗,一個用於 Facebook,一個用於 Twitter。 有沒有更好的方法來解組這樣的 json?
您提供的示例應該可以工作,它只會將您的字符串之一留空。
如果你想用 2 個不同的結構替換Social
,你可以讓Social
成為兩個新結構都實現的接口。 然后使用json.RawMessage
在social
中延遲 json 的解組。 這是 godocs 中給出的示例:
import (
"encoding/json"
"fmt"
"log"
)
func main() {
type Color struct {
Space string
Point json.RawMessage // delay parsing until we know the color space
}
type RGB struct {
R uint8
G uint8
B uint8
}
type YCbCr struct {
Y uint8
Cb int8
Cr int8
}
var j = []byte(`[
{"Space": "YCbCr", "Point": {"Y": 255, "Cb": 0, "Cr": -10}},
{"Space": "RGB", "Point": {"R": 98, "G": 218, "B": 255}}
]`)
var colors []Color
err := json.Unmarshal(j, &colors)
if err != nil {
log.Fatalln("error:", err)
}
for _, c := range colors {
var dst interface{}
switch c.Space {
case "RGB":
dst = new(RGB)
case "YCbCr":
dst = new(YCbCr)
}
err := json.Unmarshal(c.Point, dst)
if err != nil {
log.Fatalln("error:", err)
}
fmt.Println(c.Space, dst)
}
}
在此示例中,他們使用字符串來指示要解組Point
的結構。 在您的情況下,您可能需要首先將social
解組為map[string]interface{}
並根據字段確定應使用哪種類型。 或者在User
結構中添加一個socialType
字段。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.