解组忽略空字段 [英] unmarshal ignore empty fields

查看:58
本文介绍了解组忽略空字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在成功提交用户详细信息时,我从客户端获得了JSON.

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

由于未更新JSON中的某些元素,因此可以跳过.

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

在Go服务器端,我定义了一个等效的结构.

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

服务器成功将JSON字节编组到结构中.

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"`
}

但是对于未从客户端收到的字段,默认情况下取消对字符串的硬编码解组为nil,对字符串数组的空数组进行硬编码.

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

例如,如果我得到json {"Id":64,"Name":"Ryan"}
我不希望解组将其转换为 {"Id":十六进制,"Name":十六进制,"Age":nil} .
为简单起见,我希望它是 {"Id":十六进制,"Name":十六进制}

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代码: http://play.golang.org/p/3dZq0nf68R

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

推荐答案

您有点困惑, fmt.Printf(%+ v",动物)打印Go结构,该结构将始终打印所有指定的字段.

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

但是,如果将其转换回json,它将省略nil字段.

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

检查 http://play.golang.org/p/Q2M5oab2UX

这篇关于解组忽略空字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆