将JSON解组为Golang类型Big.Float。

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

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.

huangapple
  • 本文由 发表于 2016年5月1日 11:35:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/36962774.html
匿名

发表评论

匿名网友

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

确定