doubei8168 2015-12-01 16:19
浏览 153

Go lang json.Marshall()忽略ByteArray字段中的遗弃

Please see below.

https://play.golang.org/p/HXrqLqYIgz

My expected value is:

{"Byte2":0,"Name":"bob"}

But Actual:

{"ByteArray":[0,0,0,0],"Byte2":0,"Name":"bob"}

According to the document (https://golang.org/pkg/encoding/json/)

The empty values are false, 0, any nil pointer or interface value, and any array, slice, map, or string of length zero.

Therefore, json.Marshall() ignores omitempty-tag, because [0 0 0 0] is not zero-length nor 0 nor nil.

And now, to get the expected value, What should we do?

  • 写回答

2条回答 默认 最新

  • donglan9651 2015-12-01 16:24
    关注

    You'll have to either make ByteArray a slice, or a pointer to array:

    type A struct {
        ByteArray *[4]byte `json:",omitempty"`
        Byte1     byte     `json:",omitempty"`
        Byte2     byte
        Name      string `json:",omitempty"`
    }
    

    Playground: https://play.golang.org/p/nYBqGrSA1L.

    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题