我在问自己遇到的一个错误。我正在制作一个 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}就像我之前说的,我不仅发送用户,它可能是很多不同的对象,那么我该如何实现呢?我的第二个想法更好吗?如果是,我该如何编码?
1 回答
三国纷争
TA贡献1804条经验 获得超7个赞
在 golang 中,json.Marshal 处理嵌套结构、切片和映射。
package main
import (
"encoding/json"
"fmt"
)
type Animal struct {
Descr description `json:"description"`
Age int `json:"age"`
}
type description struct {
Name string `json:"name"`
}
func main() {
d := description{"Cat"}
a := Animal{Descr: d, Age: 15}
data, _ := json.MarshalIndent(a,"", " ")
fmt.Println(string(data))
}
此代码打印:
{
"description": {
"name": "Cat"
},
"age": 15
}
当然,解组的工作方式完全相同。如果我误解了这个问题,请告诉我。
https://play.golang.org/p/t2CeHHoX72
- 1 回答
- 0 关注
- 219 浏览
添加回答
举报
0/150
提交
取消
