带有 json 接口的结构体

我在问自己遇到的一个错误。我正在制作一个 API,它发送一个看起来像这样的响应:


var StatusBack struct {

    Description string // to describe the error/the result

    StatusId int // the status number (500 Internal error, 200 OK...)

}

// client get 

{

    description: "{surname: \"Xthing\", firstname: \"Mister\"}"

    status_id: 200

}

所以我的想法是用 Marshal 将 json 变成一个字符串,然后 Marshal 第二次使用 StatusBack 结构来发送它。但是,它并没有使我真正想要的是获取包含另一个对象的对象。客户端只得到一个包含字符串的对象。问题是,我不只发送用户作为结果,所以就像我在下面展示的那样,我认为我需要一个接口


var StatusBack struct {

    Description string // to describe the error

    Result <Interface or object, I don t know> // which is the result

    StatusId int // the status number (500 Internal error, 200 OK...)

}

// client get 

{

    description: "User information",

    result: {

        surname: "Xthing",

        firstname: "Mister"

    },

    status_id: 200

}

就像我之前说的,我不仅发送用户,它可能是很多不同的对象,那么我该如何实现呢?我的第二个想法更好吗?如果是,我该如何编码?


跃然一笑
浏览 238回答 1
1回答

三国纷争

在 golang 中,json.Marshal 处理嵌套结构、切片和映射。package mainimport (&nbsp; &nbsp; "encoding/json"&nbsp; &nbsp; "fmt")type Animal struct {&nbsp; &nbsp; Descr description `json:"description"`&nbsp; &nbsp; Age&nbsp; &nbsp;int&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;`json:"age"`}type description struct {&nbsp; &nbsp; Name string `json:"name"`}func main() {&nbsp; &nbsp; d := description{"Cat"}&nbsp; &nbsp; a := Animal{Descr: d, Age: 15}&nbsp; &nbsp; data, _ := json.MarshalIndent(a,"", "&nbsp; ")&nbsp; &nbsp; fmt.Println(string(data))}此代码打印:{&nbsp; "description": {&nbsp; &nbsp; "name": "Cat"&nbsp; },&nbsp; "age": 15}当然,解组的工作方式完全相同。如果我误解了这个问题,请告诉我。https://play.golang.org/p/t2CeHHoX72
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go