为 json.RawMessage 类型调用 MarshalJSON 的 Json 错误

Jis*_*hap 5 json marshalling go

尝试编组此结构时出现以下错误

json:为 json.RawMessage 类型调用 MarshalJSON 时出错:JSON 输入意外结束

对于以下结构的对象

type Chart struct {
    ID          int             `json:"id,omitempty" db:"id"`
    Name        string          `json:"name,omitempty" db:"name"`
    Type        string          `json:"type,omitempty" db:"type"`
    DashboardID int             `json:"dashboard_id,omitempty"`
    SourceType  string          `json:"source_type,omitempty" db:"source_type"`
    Data        json.RawMessage `json:"graph_data,ommitempty"`
}

func main() {
    chart := Chart{}
    chart.ID = 1
    chart.Name = "Jishnu"
    str, err := json.Marshal(chart)
    fmt.Println(err)
}
Run Code Online (Sandbox Code Playgroud)

Jis*_*hap 8

通过制作Chart.Data指针固定

 Data        *json.RawMessage `json:"data,ommitempty"`
Run Code Online (Sandbox Code Playgroud)

Go 1.8(在撰写本文时当前为 rc3)将正确处理指针和非指针 json.RawMessage 的编组。

修复提交:https : //github.com/golang/go/commit/1625da24106b610f89ff7a67a11581df95f8e234

  • 我知道这已经很旧了,但我正在处理同样的问题,因此可能值得指出“ommitempty”中的拼写错误。所有其他都有正确的值“omitempty”。 (2认同)