最近试了试go中对json null字段进行转换,代码如下:
struct 转 json:
package main import ( "encoding/json" "fmt" "os" ) var d = []byte(`{ "world":[{"data": 2251799813685312}, {"data": null}]}`) type jsonobj struct{ World []World } type World struct{ Data *int64 } func main() { var data jsonobj jerr := json.Unmarshal(d, &data) fmt.Println(jerr) var t int64 = 111 mardata := jsonobj{World: []World{World{Data: &t}, World{Data: nil}}} b, _ := json.Marshal(mardata) os.Stdout.Write(b) }
json 转struct:
package main import "fmt" import "encoding/json" type jsons struct { Data1 *int64 Data2 *int64 } var d = []byte(`{"data1": 12121, "data2" : null}`) func main() { var data jsons json.Unmarshal(d, &data) fmt.Println(*(data.Data1)) if data.Data2 == nil { fmt.Println("data2 is nil") } }