Golang将json字符串转json对象
注意 结构体里成员首字母必须大写才可以读取数据
package main
import (
"encoding/json"
"fmt"
)
func main() {
type Response struct {
RequestID string `json:"RequestId"`
SendStatusSet []map[string]interface{} `json:"SendStatusSet"`
}
type r struct {
Response Response `json:"Response"`
}
txt := `{
"Response": {
"SendStatusSet": [{
"SerialNo": "5000:1045710669157053657849499619",
"PhoneNumber": "+8618511122233",
"Fee": 1,
"SessionContext": "test",
"Code": "Ok",
"Message": "send success",
"IsoCode": "CN"
},
{
"SerialNo": "5000:104571066915705365784949619",
"PhoneNumber": "+8618511122266",
"Fee": 1,
"SessionContext": "test",
"Code": "Ok",
"Message": "send success",
"IsoCode": "CN"
}
],
"RequestId": "a0aabda6-cf91-4f3e-a81f-9198114a2279"
}
}`
// fmt.Println(txt)
p := &r{}
err := json.Unmarshal([]byte(txt), p)
fmt.Println(err)
fmt.Println(*p)
type simple struct {
Response map[string]interface{}
}
zzz := new(simple)
err = json.Unmarshal([]byte(txt), zzz)
fmt.Println(err)
fmt.Println("--------------")
fmt.Println(*zzz)
simpleJSON := `{"Name":"Xiao mi 6","ProductID":1,"Number":10000,"Price":2499,"IsOnSale":true}`
type k struct {
Name string
}
kk := &k{}
err = json.Unmarshal([]byte(simpleJSON), kk)
fmt.Println(err)
fmt.Println(*kk)
}