我需要通过保留键和值的顺序将 JSON 数据取消到映射中。这是一个 JSON 数据示例:{ "31ded736-4076-4b1c-b38f-7e8d9fa78b41": { "Name": "Requested", "Items": [ { "ID": "c7ac5b7f-59b0-45e3-82fb-b3b0afc05f55", "GroupName": "First task" , "NumQuestion": "10" ,"Score":"10"}, {"ID": "17acf9a1-b2c7-46c6-b975-759b9d9f538d", "GroupName": "Test1" , "NumQuestion": "20" ,"Score":"5" } ] }, "115f7d04-3075-408a-b8ce-c6e46fe6053f": { "Name": "To do", "Items": [ { "ID": "c7ac5b7f-59b0-45e3-82fb-b3b0afc05f56", "GroupName": "First task" , "NumQuestion": "5" ,"Score":"10"} ] }, "9bcf1415-3a41-43b6-a871-8de1939a75c4": { "Name": "In Progress", "Items": [ { "ID": "c7ac5b7f-59b0-45e3-82fb-b3b0afc05f57", "GroupName": "Second task" , "NumQuestion": "10" ,"Score":"5"} ] }, "2f6c1455-6cf9-4009-b86b-de0a0d2204a1": { "Name": "Done", "Items": [ { "ID": "c7ac5b7f-59b0-45e3-82fb-b3b0afc05f58", "GroupName": "Third task" , "NumQuestion": "20" , "Score":"7"} ] } }这是我的代码:var GroupTestListUpdate = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { type Item struct { ID string `json:"id"` GroupName string `json:"groupName"` NumQuestion string `json:"numQuestion"` Score string `json:"score"` } type Input struct { Name string `json:"name"` Items []Item `array:"item"` } var objmap map[string]Input reqBody, err := ioutil.ReadAll(r.Body) if err != nil{ http.Error(w, "can't read body", http.StatusBadRequest) return } json.Unmarshal(reqBody, &objmap) fmt.Println(objmap)})问题:我想知道如何保留键和值的顺序。每次尝试此代码时,我都得到了相同的输出,所以我想知道地图中的顺序不是完全随机的吗?
1 回答
呼啦一阵风
TA贡献1802条经验 获得超6个赞
是的。
您可以重写自定义地图类型上的方法,该方法将允许您保留顺序。UnmarshalJSON
例如,这里有一个库可以做到这一点:https://github.com/iancoleman/orderedmap。
- 1 回答
- 0 关注
- 114 浏览
添加回答
举报
0/150
提交
取消