duanbi1983 2014-08-05 00:02
浏览 68
已采纳

Golang解组忽略空字段

I get a JSON from a client on the successful submit of user details.

Some element in the JSON can be skipped since they were not updated.

On the Golang server side, I have an equivalent struct defined.

The server successfully marshals the JSON bytes into the struct.

type user struct {
    Id       *int64  `json:",omitempty"`
    Name     *string `json:",omitempty"`
    Age      *int64  `json:",omitempty"`
}

But for fields which are not recieved from client, unmarshal by default hard-codes nil for string and empty array for string array.

For example, if I get the json { "Id" : 64, "Name" : "Ryan" },
I don't want unmarshal to convert it to {"Id" : some hexadecimal, "Name" : some hexadecimal, "Age" : nil}.
To make it simple, I would expect it to be {"Id" : some hexadecimal, "Name" : some hexadecimal }

How can I totally ignore the field and map what I get?

Goplayground Code : http://play.golang.org/p/3dZq0nf68R

Appreciate your response.

  • 写回答

1条回答 默认 最新

  • dtnpf35197 2014-08-05 00:20
    关注

    You are a little bit confused, fmt.Printf("%+v", animals) prints the Go structs, which will always have all fields specified printed out.

    However, if you convert it back to json, it will omit the nil fields.

    Check http://play.golang.org/p/Q2M5oab2UX

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?