简体   繁体   English

golang-将结构改成json

[英]golang - fomatting struct to json

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"
    }
  ]
}

You've missed a few quotes: 您错过了一些引号:

Pointer   string `json:pointer,omitempty"`
Parameter string `json:parameter,omitempty"`
                  // ^^^ Here.

Playground: https://play.golang.org/p/P3oHK29VKQ . 游乐场: https : //play.golang.org/p/P3oHK29VKQ

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM