golang json序列化得到的数据有\的问题
我们在对外提供API接口,返回响应的时候,很多时候需要使用如下的数据结构

type Response struct {Code int         `json:"code"`Msg  string      `json:"msg"`Data interface{} `json:"data"`
}


该API接口返回一个状体码,状态信息,以及具体的值。但是具体的值可能根据各个接口的不同而不同。
在实际的开发过程中我们可能会得到一个实际的数据值,并将这个值赋值给data,然后json序列化返回给调用方。
这时如果你得到的data是一个经过json序列化之后的字符串,类似于{"Name":"happy"},然后再将这个字符串赋值给data,此时将response序列化得到的string,如下 {“code”:1,”msg”:”success”,”data”:”{\”Name\”:\”Happy\”}”}
我们会发现之前已经序列化好的字符串,每一个都多了\,这是因为转义引起的问题。解决方法
1 直接将未序列化的data赋值给data

package mainimport ("encoding/json""fmt"
)type Response struct {Code int         `json:"code"`Msg  string      `json:"msg"`Data interface{} `json:"data"`
}
type People struct {Name string
}func main() {data := People{Name: "happy"}response := &Response{Code: 1,Msg:  "success",Data: data,}b, err := json.Marshal(&response)if err != nil {fmt.Println("err", err)}fmt.Println(string(b))
}


使用json 的RawMessage 将转义后的string,赋值给data

package mainimport ("encoding/json""fmt"
)type Response struct {Code int         `json:"code"`Msg  string      `json:"msg"`Data interface{} `json:"data"`
}
type People struct {Name string
}func main() {data := `{"Name":"Happy"}`response := &Response{Code: 1,Msg:  "success",Data: json.RawMessage(data),}b, err := json.Marshal(&response)if err != nil {fmt.Println("err", err)}fmt.Println(string(b))
}


通过使用json的json.RawMessage(data)函数将其转换一下,这样也能保证不存在转义符。