Go json,编组空值

huangapple go评论77阅读模式
英文:

Go json, marshal empty value

问题

我在使用omitempty和空值方面遇到了问题。请参考这个示例。我有一个值,我不希望在编组时被忽略,即使值为""。这明确意味着我想要清除该值,因此我希望得到编组结果:

{"cf_objectType":"Product","cf_isLocked":"No","cf_ErrorMessage":""}

我尝试了这里的指向字符串的方法,但出于某种原因,我不喜欢这种方法。是否有其他的替代方法?例如,为什么我们没有一个类似于omitempty的标签,比如omitnull之类的标签?

编辑

为了澄清,如下所示:

m := Metadata{
	ObjectType:   "Product",
	Locked:       "No",
	ErrorMessage: "",

}

我希望对此结构体进行编组函数的结果是:

{
    "cf_objectType":"Product",
    "cf_isLocked":"No",
    "cf_ErrorMessage":""
}

并且

m := Metadata{
	ObjectType:   "Product",
	Locked:       "No",
}

结果应该是:

{
    "cf_objectType":"Product",
    "cf_isLocked":"No",
}
英文:

I'm having problems with omitempty and empty values. Please see this playground example. I have a value which I don't want to be ignored during marshal in case of value "". This explicitly means that I want to clear the value and therefore I want to have marshalled result:

{"cf_objectType":"Product","cf_isLocked":"No","cf_ErrorMessage":""}

Now I tried the pointer-to-string approach here, but for some reason I don't like this. Are there any alternatives known? For example, why don't we have a tag (just like omitempty) like omitnull or something?

EDIT

To clarify, see below

m := Metadata{
	ObjectType:   "Product",
	Locked:       "No",
	ErrorMessage: "",

}

I want the result of the marshal function on this struct to be:

{
    "cf_objectType":"Product",
    "cf_isLocked":"No",
    "cf_ErrorMessage":""
}

AND

m := Metadata{
	ObjectType:   "Product",
	Locked:       "No",
}

result shoulde be:

{
    "cf_objectType":"Product",
    "cf_isLocked":"No",
}

答案1

得分: 2

如果你不想省略空值,只需删除omitempty标签。

https://play.golang.org/p/6axA2OIG6O

英文:

If you don't want to omit empty values, just remove omitempty tag

https://play.golang.org/p/6axA2OIG6O

答案2

得分: 1

关于你最后的评论(我没有足够的声望来回复):

> 好的,这个方法有效:play.golang.org/p/TYk67p6i_b 但是在我的结构定义中,我有一种混合了字符串和*字符串的情况。而且我也不能在没有var emptyString = ""的情况下“填充”值,对吗?

请参考这个(Golang:将nil字符串指针设置为空字符串)的帖子

英文:

With regard to your last comment (for which I don't have enough reputation to reply to):

> Ok, this works: play.golang.org/p/TYk67p6i_b But then I have a mix of
> string and *string in my struct definition. And I also can't "fill"
> the value without having the var emptyString = "", right?

See this (Golang: set nil string pointer to empty string) post

huangapple
  • 本文由 发表于 2017年7月27日 18:32:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/45348256.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定