我有一些 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 关注
- 211 浏览
添加回答
举报
0/150
提交
取消