在我的应用程序中,我得到一些未指定的 json 字符串,并希望循环遍历 json 字符串的值。我使用函数 json.Unmarshal() 从 json 值获取对象列表。效果很好。但不幸的是,我得到了 json 值的随机列表,而不是它们的原始顺序。我使用这个示例代码:
package main
import (
"encoding/json"
"fmt"
)
func main() {
jsonstr := `{
"@odata.context": "http://services.odata.org/V4/TripPinService/$metadata#People/$entity",
"@odata.id": "http://services.odata.org/V4/TripPinService/People('russellwhyte')",
"@odata.etag": "W/\"08D956FAB7E22152\"",
"@odata.editLink": "http://services.odata.org/V4/TripPinService/People('russellwhyte')",
"UserName": "russellwhyte",
"FirstName": "Russell",
"LastName": "Whyte",
"Gender": "Male",
"Concurrency": 637636457076498770
}`
var result interface{}
if err := json.Unmarshal([]byte(jsonstr), &result); err != nil {
fmt.Println("Can't convert json to object.")
fmt.Println(err.Error())
}
odataobjs := result.(map[string]interface{})
for k, v := range odataobjs {
fmt.Print(fmt.Sprintln(k, v))
}
}
Run Code Online (Sandbox Code Playgroud)
请参阅go-playground。
这可能是一些结果列表: …