我有一些 JSON 代碼,看起來像:{ "message_id": "12345", "status_type": "ERROR", "status": { "x-value": "foo1234", "y-value": "bar4321" }}或者看起來像這樣。如您所見,“status”元素根據 status_type 從標準字符串對象更改為字符串數組對象。{ "message_id": "12345", "status_type": "VALID", "status": { "site-value": [ "site1", "site2" ] }}我想我需要讓我的“狀態”結構采用像“map[string]interface{}”這樣的地圖,但我不確定如何做到這一點。您也可以在操場上看到這里的代碼。http://play.golang.org/p/wKowJu_lngpackage mainimport ( "encoding/json" "fmt")type StatusType struct { Id string `json:"message_id,omitempty"` Status map[string]string `json:"status,omitempty"`}func main() { var s StatusType s.Id = "12345" m := make(map[string]string) s.Status = m s.Status["x-value"] = "foo1234" s.Status["y-value"] = "bar4321" var data []byte data, _ = json.MarshalIndent(s, "", " ") fmt.Println(string(data))}
3 回答
交互式愛情
TA貢獻1712條經驗 獲得超3個贊
我想通了,我想..
package main
import (
"encoding/json"
"fmt"
)
type StatusType struct {
Id string `json:"message_id,omitempty"`
Status map[string]interface{} `json:"status,omitempty"`
}
func main() {
var s StatusType
s.Id = "12345"
m := make(map[string]interface{})
s.Status = m
// Now this works
// s.Status["x-value"] = "foo1234"
// s.Status["y-value"] = "bar4321"
// And this works
sites := []string{"a", "b", "c", "d"}
s.Status["site-value"] = sites
var data []byte
data, _ = json.MarshalIndent(s, "", " ")
fmt.Println(string(data))
}
- 3 回答
- 0 關注
- 244 瀏覽
添加回答
舉報
0/150
提交
取消
