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 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥15 想问一下树莓派接上显示屏后出现如图所示画面,是什么问题导致的
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败