【Golang】string类型进行json转换成struct类型

string类型进行json转换成struct类型

问题解释

一般情况下, 将json转化成struct时, 对于 "{\"name\":\"xxx\",\"age\":12}" 这种可以直接进行json反序列化成struct.

type Person struct {
	Name string `json:"name"`
	Age int `json:"age"`
}
var p Person
pStr := "{\"name\":\"xxx\",\"age\":12}"
err := json.Unmarshal([]byte(pStr), &p)

但是对于`"{\"name\":\"xxx\",\"age\":12}"`这种string, 反序列化后会报错 json: cannot unmarshal string into Go value of type XXX, 这说明string的数据本身已经是string类型, 不能直接转换成struct.

解决方式

进行json.Unmarshal之前, 先通过strconv.Unquote(pStr)返回字符串的值.
这样就能解析成struct了.

posted @ 2021-03-25 18:02  EmbraceU  阅读(2695)  评论(0编辑  收藏  举报