golang json序列化得到的数据有\的问题

我们在对外提供API接口,返回响应的时候,很多时候需要使用如下的数据结构

type Response struct {
    Code int         `json:"code"`
    Msg  string      `json:"msg"`
    Data interface{} `json:"data"`
}
{"Name":"happy"}
解决方法

1 直接将未序列化的data赋值给data

package main

import (
    "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 main

import (
    "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)函数将其转换一下,这样也能保证不存在转义符。