我有一个结构
type Order struct {
ID string `json:"id"`
CustomerMobile string `json:"customerMobile"`
CustomerName string `json:"customerName"`
}
和json数据:
[{"Key":"S001", "Record":{"id":"SOO1","customerMobile":"12344566","customerName":"John"}}]
如何从上面的json对象访问customerMobile键?
我在谷歌做了一些研究,我发现了以下解决方案,但是当我申请上述要求时,它无效。它使用简单的json格式。
jsonByteArray := []byte(jsondata)
json.Unmarshal(jsonByteArray, &order)
答案 0 :(得分:2)
您需要解组成代表整个JSON对象的内容。您的Order
结构定义了它的一部分,因此只需定义其余部分,如下所示:
package main
import (
"encoding/json"
"fmt"
)
type Order struct {
ID string `json:"id"`
CustomerMobile string `json:"customerMobile"`
CustomerName string `json:"customerName"`
}
type Thing struct {
Key string `json:"Key"`
Record Order `json:"Record"`
}
func main() {
jsonByteArray := []byte(`[{"Key":"S001", "Record":{"id":"SOO1","customerMobile":"12344566","customerName":"John"}}]`)
var things []Thing
err := json.Unmarshal(jsonByteArray, &things)
if err != nil {
panic(err)
}
fmt.Printf("%+v\n", things)
}
答案 1 :(得分:0)
试一试:https://play.golang.org/p/pruDx70SjW
package main
import (
"encoding/json"
"fmt"
)
const data = `[{"Key":"S001", "Record":{"id":"SOO1","customerMobile":"12344566","customerName":"John"}}]`
type Orders struct {
Key string
Record Order
}
type Order struct {
ID string
CustomerMobile string
CustomerName string
}
func main() {
var orders []Orders
if err := json.Unmarshal([]byte(data), &orders); err != nil {
panic(err)
}
fmt.Printf("%+v\n", orders)
}
在这种情况下,我省略了struct tags