英文:
golang - fomatting struct to json
问题
有人知道如何为多级结构设置标签名称吗?
结构的顶层标签名称可以正常工作,但是所有子级的标签名称与结构中的名称相同。尝试将所有标签名称设置为小写。
代码可以在这里运行:
package main
import (
"encoding/json"
"log"
)
type Source struct {
Pointer string `json:"pointer,omitempty"`
Parameter string `json:"parameter,omitempty"`
}
type Error struct {
Status int `json:"status,omitempty"`
Source *Source `json:"source,omitempty"`
Title string `json:"title,omitempty"`
Detail string `json:"detail,omitempty"`
}
type Errors struct {
Errors *[]Error `json:"errors"`
}
func main() {
errors := new(Errors)
errors.Errors = new([]Error)
error := new(Error)
error.Source = new(Source)
error.Source.Pointer = "pointer"
error.Status = 401
error.Title = "title"
error.Detail = "detail"
*errors.Errors = append(*(errors.Errors), *error)
response, _ := json.Marshal(errors)
log.Println("response", string(response))
}
输出:
{
"errors": [
{
"status": 400,
"source": {
"pointer": "pointer",
"parameter": ""
},
"title": "title",
"detail": "detail"
}
]
}
英文:
Does anyone know how to set the tag names for multilevel structs?
The top level tag-names of the struct works ok, but all sublevels tag names have the same name as in the struct. Trying to set all tag-name to lowercase.
The code can be run here:
package main
import (
"encoding/json"
"log"
)
type Source struct {
Pointer string `json:pointer,omitempty"`
Parameter string `json:parameter,omitempty"`
}
type Error struct {
Status int `json:"status,omitempty"`
Source *Source `json:"source,omitempty"`
Title string `json:"title,omitempty"`
Detail string `json:"detail,omitempty"`
}
type Errors struct {
Errors *[]Error `json:"errors"`
}
func main() {
errors := new(Errors)
errors.Errors = new([]Error)
error := new(Error)
error.Source = new(Source)
error.Source.Pointer = "pointer"
error.Status = 401
error.Title = "title"
error.Detail = "detail"
*errors.Errors = append(*(errors.Errors), *error)
response, _ := json.Marshal(errors)
log.Println("response", string(response))
}
Output:
{
"errors": [
{
"status": 400,
"source": {
"Pointer": "pointer",
"Parameter": ""
},
"title": "title",
"detail": "detail"
}
]
}
答案1
得分: 0
你错过了几个引号:
Pointer string `json:"pointer,omitempty"`
Parameter string `json:"parameter,omitempty"`
// ^^^ 在这里。
Playground: https://play.golang.org/p/P3oHK29VKQ.
英文:
You've missed a few quotes:
Pointer string `json:pointer,omitempty"`
Parameter string `json:parameter,omitempty"`
// ^^^ Here.
Playground: https://play.golang.org/p/P3oHK29VKQ.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论