dttphb59319 2016-08-09 22:15
浏览 441
已采纳

如何在Golang中将具有两种不同数据类型的JSON数组解析为结构

I have JSON that looks like this:

{
    "a": [
          [
              "12.58861425",
              10.52046452
          ],
          [
              "12.58861426",
              4.1073
          ]
        ]
    "b": [
          [
              "12.58861425",
              10.52046452
          ],
          [
              "12.58861426",
              4.1073
          ]
        ]
    "c": "true"
    "d": 1234
}
        

I want to unmarshall this into a struct I created:

type OrderBook struct {
    A [][2]float32 `json:"a"`
    B [][2]float32 `json:"b"`
        C string `json:"c"`
    D uint32 `json:"d"`
}

//Note this won't work because the JSON array contains a string and a float value pair rather than only floats.

Normally I would then convert this JSON into a struct in Golang as so:

orders := new(OrderBook)
err = json.Unmarshal(JSON, &orders)

Since I can't define the type struct to match the JSON this won't work. Doing a bit of reading, I think Unmarshal-ing into an interface, and then using the interface data through type checking may be a solution.

Am I going in the right direction with this?
A template showing how I might go about using the data once it's in the interface would really help.

</div>
  • 写回答

1条回答 默认 最新

  • duanjieyi6582 2016-08-10 04:37
    关注

    Why not just leave out declaring the types of the A and B slices like so?

    data := []byte(`{"a": [["12.58861425",10.52046452],["12.58861426",4.1073]],"b": [["12.58861425",10.52046452],["12.58861426",4.1073]],"c": "true","d": 1234}`)
    
    type OrderBook struct {
        A [][2]interface{} `json:"a"`
        B [][2]interface{} `json:"b"`
        C string           `json:"c"`
        D uint32           `json:"d"`
    }
    orders := new(OrderBook)
    err := json.Unmarshal(data, &orders)
    if err != nil {
        fmt.Printf(err.Error())
    } else {
        fmt.Printf("%s
    ", orders.A[0][0].(string))     
        fmt.Printf("%f
    ", orders.A[0][1].(float64))
    }
    

    There's an example in the playground: https://play.golang.org/p/0MUY-yOYII

    I must disagree with evanmcdonnal, there are certainly use cases where where rolling your own Unmarshaller makes sense, this I do not believe is one of them. It doesn't get much simpler than what is shown here.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?