小编jus*_*wit的帖子

有没有更简单的方法使用Golang JSON编码在JSON对象上添加图层?

Go中开箱即用的JSON编码非常好,但我需要通过添加图层来使输出与特定格式匹配.我已经找到了一种方法,但希望有一种比我正在做的方式更简单的方法.

下面是我如何做的一个例子.

import (
  "bytes"
  "encoding/json"
  "encoding/xml"
  "fmt"
)
type Query struct {
    XMLName xml.Name      `xml:"http://marklogic.com/appservices/search query" json:"-"`
    Format  int           `xml:"-" json:"-"`
    Queries []interface{} `xml:",any" json:"queries"`
}
type TermQuery struct {
    XMLName xml.Name `xml:"http://marklogic.com/appservices/search term-query" json:"-"`
    Terms   []string `xml:"http://marklogic.com/appservices/search text" json:"text"`
    Weight  float64  `xml:"http://marklogic.com/appservices/search weight,omitempty" json:"weight,omitempty"`
}
// use fakeQuery to avoid an infinite loop
type fakeQuery Query

//MarshalJSON for Query struct in a special way to add wraping {"query":...}
func (q Query) MarshalJSON() ([]byte, error) {
    return wrapJSON(`query`, fakeQuery(q)) …
Run Code Online (Sandbox Code Playgroud)

json go

5
推荐指数
1
解决办法
1225
查看次数

标签 统计

go ×1

json ×1