[英]Go json, marshal empty value
I'm having problems with omitempty
and empty values. 我在
omitempty
和空值方面遇到问题。 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? 例如,我们为什么不有一个标签(就像
omitempty
等) omitnull
什么?
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",
}
If you don't want to omit empty values, just remove omitempty
tag 如果您不想省略空值,只需删除
omitempty
标签
https://play.golang.org/p/6axA2OIG6O https://play.golang.org/p/6axA2OIG6O
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.
好的,这可行 : play.golang.org/p/TYk67p6i_b但是我在结构定义中混合了字符串和* string。 And I also can't "fill" the value without having the
var emptyString = ""
, right?而且我也不能在没有
var emptyString = ""
情况下“填充”值,对吗?
See this (Golang: set nil string pointer to empty string) post 看到这个(Golang:将nil字符串指针设置为空字符串)帖子
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.