如何解决将值附加到 c.Json 响应
我想在我的代码返回的响应中附加一个值,这是我已经拥有的:
publisherShare := 25 // I also have this variable that want to append to the returned response.
c.JSON(http.StatusOK,nf) // nf is a row found and returned from database.
这会返回这样的 json:
{
"id": 105324,"title": "test title","last_update": "2021-03-10T12:50:37+03:30","created_at": "2021-03-10T12:50:36+03:30","updated_at": "2021-05-05T05:46:39.352859604Z"
}
我需要一个这样的 json 结果:
{
"id": 105324,"updated_at": "2021-05-05T05:46:39.352859604Z","publisher_share": 25 // I want this to be added.
}
这是我迄今为止尝试过的,但它改变了架构并且不再向后兼容:
c.Json(http.StatusOK,gin.H{"book": nf,"publisher_share": publisherShare})
但这不是我想要的 json 结果。我想要 publisher_share
和其他字段,就像我上面提到的 json 结果一样。
解决方法
您可以将发布者共享添加到与此相同的类型
type nfType struct {
// All of the db row fields
PublisherShare int `json:"publisher_share,omitempty" db:"-"`
}
,
只需创建一个与您的 json 响应结构匹配的结构。关键是添加额外的 fild 像
type Responce struct {
// other fields. They have to be written in same way to keep conventions
// (Go-ish name and needed name as tag)
PublisherShare int `json:"publisher_share"`
}
然后当您处理响应时,您可以解组和编组 json。
responce := Responce{PublisherShare: 25}
err := json.Unmarshal(bytes,&responce)
if err != nil {
//handle error
}
newResponce,err := jsom.Marshal(responce)
if err != nil {
//handle error
}
// newResponce is now in form you want
,
定义一个新类型。它嵌入了 db 行的类型,并且有一个用于额外值的字段。例如:如果 db 行的类型是 DatabaseRow
:
type CompleteReturn struct {
DatabaseRow
PublisherShare int `json:"publisher_share"`
}
以后将其用作:
complete := CompleteReturn{
DatabaseRow: nf,// Serialize in json as before
PublisherShare: 25,// Serialize in json as publisher_share
}
c.Json(http.StatusOk,complete)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。