dongyi5570 2015-05-15 15:34
浏览 247
已采纳

如何将以下划线开头的字段编组为JSON [Golang]

Go's encoding/json package has some brilliant JSON marshalling functionality, and for all intents and purposes it's exactly what I need. But the problem arises when I want to try and marshal something I want to insert into a MongoDB instance.

MongoDB understands _id as an indexed identifier, but Go's JSON package only marshals exported fields so MongoDB creates its own ID for the document when I save, which I do not want, and I haven't even begun to test the implications it will have unmarshalling to a struct.

Is there a way to make the JSON marshaller include fields beginning with an underscore without writing a whole new one?

  • 写回答

1条回答 默认 最新

  • dongyou9373 2015-05-15 16:44
    关注

    You can easily rename the fields. The Go name should start with an uppercase to be exported, but the json name can be anything compliant with json.

    Here is an example borrowed to the encoding/json package documentation:

     package main
    
    import (
        "encoding/json"
        "fmt"
        "os"
    )
    
    func main() {
        type ColorGroup struct {
            ID     int       `json:"_id"`
            Name   string
            Colors []string
        }
        group := ColorGroup{
            ID:     1,
            Name:   "Reds",
            Colors: []string{"Crimson", "Red", "Ruby", "Maroon"},
        }
        b, err := json.Marshal(group)
        if err != nil {
            fmt.Println("error:", err)
        }
        os.Stdout.Write(b)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?