Go语言学习笔记7: jsoniter 解码json 使用指南

范例:

var jsonIterator = jsoniter.ConfigCompatibleWithStandardLibrary	    //实例化工具类
var response struct {    //解码承载结构体
	Result int `json:"result"`
	TaskId string `json:"task_id"`
}

jsonIterator.UnmarshalFromString(resultString, &response)

需要注意几个点:

1. 结构体中的字段,首字母要大写

2.需要读取的字段,要写json注解,例如:

Result int `json:"result"`

3.解码的时候,需要传入承载结构体的地址:

jsonIterator.UnmarshalFromString(resultString, &response)

4.使用omitempty,在marshall时忽视不需要的字段

type faceStruct struct {
	Age *int `json:"age,omitempty"`
	Emotion int `json:"emotion,omitempty"`
}

{“age”:0,"emotion":0}, age会被解析, 而emotion会被忽视

猜你喜欢

转载自blog.csdn.net/u012560213/article/details/80996755