doujiang5211 2017-11-20 20:19
浏览 781
已采纳

前往:将JSON字符串转换为map [string] interface {}

I'm trying to create a JSON representation within Go using a map[string]interface{} type. I'm dealing with JSON strings and I'm having a hard time figuring out how to avoid the JSON unmarshaler to automatically deal with numbers as float64s. As a result the following error occurs.

Ex. "{ 'a' : 9223372036854775807}" should be map[string]interface{} = [a 9223372036854775807 but in reality it is map[string]interface{} = [a 9.2233720368547758088E18]

I searched how structs can be used to avoid this by using json.Number but I'd really prefer using the map type designated above.

  • 写回答

1条回答 默认 最新

  • dongsi7759 2017-11-20 20:36
    关注

    The go json.Unmarshal(...) function automatically uses float64 for JSON numbers. If you want to unmarshal numbers into a different type then you'll have to use a custom type with a custom unmarshaler. There is no way to force the unmarshaler to deserialize custom values into a generic map.

    For example, here's how you could parse values of the "a" property as a big.Int.

    package main
    
    import (
      "encoding/json"
      "fmt"
      "math/big"
    )
    
    type MyDoc struct {
      A BigA `json:"a"`
    }
    
    type BigA struct{ *big.Int }
    
    func (a BigA) UnmarshalJSON(bs []byte) error {
      _, ok := a.SetString(string(bs), 10)
      if !ok {
        return fmt.Errorf("invalid integer %s", bs)
      }
      return nil
    }
    
    func main() {
      jsonstr := `{"a":9223372036854775807}`
      mydoc := MyDoc{A: BigA{new(big.Int)}}
    
      err := json.Unmarshal([]byte(jsonstr), &mydoc)
      if err != nil {
        panic(err)
      }
    
      fmt.Printf("OK: mydoc=%#v
    ", mydoc)
      // OK: mydoc=main.MyDoc{A:9223372036854775807}
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题
  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能
  • ¥15 远程桌面文档内容复制粘贴,格式会变化
  • ¥15 这种微信登录授权 谁可以做啊
  • ¥15 请问我该如何添加自己的数据去运行蚁群算法代码