1 回答

TA貢獻1798條經驗 獲得超3個贊
幾周后,我一直在尋找解決這個問題的方法,并查看 unmarshaler 接口和示例。然后就像icza所說的那樣,我開始查看類型之間約定的代碼,然后我就這樣解決了。如果你們有比我更好的答案,請添加答案。
數據:
[
{
"id":1,
"name":"Term 1",
"content": [
"a1",
"a2",
"a3"
]
}
]
結果:
[{ID:1 Name:Term 1 Content:[a1 a2 a3]}]
UnmarshalJSON 函數:
func (term *Term) UnmarshalJSON(data []byte) error {
tempMap := map[string]interface{}{}
if err := json.Unmarshal(data, &tempMap); err != nil {
return err
}
*term = Term{
Name: tempMap["name"].(string),
}
if tempMap["content"] != nil {
for _, v := range tempMap["content"].([]interface{}) {
(*term).Content = append((term).Content, v.(string))
}
}
return nil
}
- 1 回答
- 0 關注
- 145 瀏覽
添加回答
舉報