英文:
Unmarshal JSON into Golang type Big.Float
问题
我有一个需要将其解组为具有一些来自math
包的big.Float
字段的结构体的JSON消息。JSON字段的类型是数字类型。它给出了err = json: cannot unmarshal string into Go value of type *big.Float
的错误。
我想知道为什么它会抱怨"无法解组字符串",因为我的JSON字段是数字类型。我需要做什么才能将JSON字段解组为*big.Float
字段。
示例:
type Msg struct {
Usage0 *big.Float
Usage1 *big.Float
Usage2 *big.Float
}
// jsonMsg = {'Usage0': 31241.4543, "Usage1": 54354325423.65, ...}
err := json.Unmarshal(jsonMsg, &msg)
英文:
I have a json message that needs to be unmarshaled to a struct which has some big.Float
fields from the math
package. The json field is of type numeric. It gives me err = json: cannot unmarshal string into Go value of type *big.Float
.
I wonder why it complains "cannot unmarshal string" since my json field is numeric type. And what do I need to do to unmarshal the json filed to a *big.Float
field.
Example:
type Msg struct {
Usage0 *big.Float
Usage1 *big.Float
Usage2 *big.Float
}
// jsonMsg = {'Usage0': 31241.4543, "Usage1": 54354325423.65, ...}
err := json.Unmarshal(jsonMsg, &msg)
答案1
得分: 8
根据文档,我认为它期望将big.Float
的JSON作为字符串传递。这个示例证明了这种方法的可行性:
https://play.golang.org/p/7XKn2hhXRD
如果你无法控制JSON的格式,你可以实现自己的解码器作为替代方案。
英文:
It appears to me (based on the docs) that it expects the json for big.Float
to be passed in as strings. This play proves that to work:
https://play.golang.org/p/7XKn2hhXRD
If you cannot control the json then you can implement your own unmarshaller as an alternative.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论