英文:
Json field that can be string or bool into struct
问题
我正在使用一个API,它返回的字段有时是布尔值,有时是字符串。
像这样:
{
"unstable": true,
"unstable_reason": "ANY_REASON"
}
和
{
"unstable": false,
"unstable_reason": false
}
结构看起来像这样:
...
Unstable bool `json:"unstable"`
UnstableReason string `json:"unstable_reason,string"`
...
当我尝试使用它时,出现以下错误:
panic: json: invalid use of ,string struct tag, trying to unmarshal unquoted value into string
另一方面,当将UnstableReason
的类型设置为bool
时,也会出现错误。
当删除,string
时,我得到以下错误:
panic: json: cannot unmarshal bool into Go struct field .data.prices.unstable_reason of type string
对于我的目的来说,这个字段并不重要,所以如果有办法让它保持nil
,那也可以。
我对API没有影响。
有什么想法吗?我对Go相对较新。
英文:
I am using an API, which returns a field that is sometimes a boolean, sometimes a string.
like this:
{
"unstable":true,
"unstable_reason":"ANY_REASON"
}
and
{
"unstable":false
"unstable_reason":false
}
the struct looks like this:
...
Unstable bool `json:"unstable"`
UnstableReason string `json:"unstable_reason,string"`
...
When trying to use this, I get the following error:
panic: json: invalid use of ,string struct tag, trying to unmarshal unquoted value into string
On the other hand, when using bool
for UnstableReason
, an error occurs aswell.
When removing ,string
, I get this error:
panic: json: cannot unmarshal bool into Go struct field .data.prices.unstable_reason of type string
The field is not relevant for my purposes, so if there is a way to just let it be nil
, this would also be fine.
I have no impact on the API.
Any Ideas? I am relatively new to go.
答案1
得分: 2
你可以使用interface{}类型,如下所示:
type YourMessage struct {
Unstable bool `json:"unstable"`
UnstableReason interface{} `json:"unstable_reason"`
}
func (m YourMessage) UnstableReasonAsString() string {
return fmt.Sprint(m.UnstableReason)
}
...
m1 := &YourMessage{}
if err := json.Unmarshal([]byte(messageJson), m1); err != nil {
fmt.Println("Error", err)
} else {
fmt.Println("Unstable Reason=", m1.UnstableReasonAsString())
}
这段代码定义了一个名为YourMessage
的结构体,其中包含一个Unstable
布尔值字段和一个UnstableReason
接口类型字段。UnstableReasonAsString
方法将UnstableReason
字段转换为字符串类型并返回。在主程序中,使用json.Unmarshal
函数将JSON数据解析到m1
实例中,然后打印出UnstableReason
字段的字符串表示。
英文:
You can use interface{} type like as:
type YourMessage struct {
Unstable bool `json:"unstable"`
UnstableReason interface{} `json:"unstable_reason"`
}
func (m YourMessage) UnstableReasonAsString() string {
return fmt.Sprint(m.UnstableReason)
}
...
m1 := &YourMessage{}
if err := json.Unmarshal([]byte(messageJson), m1); err != nil {
fmt.Println("Error", err)
} else {
fmt.Println("Unstable Reason=", m1.UnstableReasonAsString())
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论