dongxun6690 2017-09-17 15:27
浏览 36
已采纳

为空的自定义类型省略JSON

I am trying to write a custom marshaler for a possibly nil database type. It is structured in the exact same way as the sql.NullFloat64 type:

type NullFloat64 sql.NullFloat64

func (ni *NullFloat64) MarshalJSON() ([]byte, error) {
    if !ni.Valid {
        return []byte("null"), nil
    }
    return json.Marshal(ni.Float64)
}

Which is a part of larger struct to be marshaled:

type Data struct {
    X time.Time `json:"x"`
    Y float32 `json:"y"`
    Stderr NullFloat64 `json:"stderr"`
}

If I try to json.Marshal() this struct, it works correctly, creating:

{"x":"2017-01-12T23:36:12-05:00","y":4,"stderr":null}

I would like to omit the JSON key entirely if the value is null. I added json:"stderr,omitempty" to Data.

Per the suggestion here, I tried just returning a nil value from MarshalJSON, but got:

json: error calling MarshalJSON for type common.NullFloat64: unexpected end of JSON input

I also tried updating Data as:

type Data struct {
    X time.Time `json:"x"`
    Y float32 `json:"y"`
    Stderr *NullFloat64 `json:"stderr,omitempty"`
}

And marshaling:

Data {
    X: datetime,
    Y: value,
    Stderr: &stderr,
}

But got the same error when returning nil from MarshalJSON as before.

So, how can I implement MarshalJSON for a custom type and omit the key when marshaling? Thanks for the help!

  • 写回答

1条回答 默认 最新

  • dongxuanchao1425 2017-09-17 18:30
    关注

    If you create you type like so:

    Data {
        X: datetime,
        Y: value,
        Stderr: nil,
    }
    

    omitempty will kick in and "do the right thing". Sadly, I'm pretty sure this won't help you.

    If you really want to omit a field based and internal state, you need to implement json.Marshaller on your structure, not its children. The easiest way to do this would be as follows:

    func (d Data) MarshalJSON() ([]byte, error) {
        if !d.Stderr.Valid {
            return json.Marshal(Data{d.X, d.Y, nil})
        }
        return json.Marshal(d)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算