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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度