duanlumei5941 2019-09-06 03:40
浏览 688

Golang JSON如何解码具有不同元素数据类型的二维数组

I need to parse json data, and I have no problem parsing object structures or pure arrays (of the same type of elements)

go version go1.12.9 darwin/amd64

Json format for ([uint8,uint8,uint32,uint16,uint16,[3][20]int16][])

[
    [
        0,
        0,
        297,
        153,
        78,
        [
            [1871, 1547, ...],
            [...],
            [...]
        ]
    ]
    ...
]

Needs to be resolved to the following structure

type HeartBeat struct {
    Template uint8
    Calssify uint8
    Index    uint32
    Tr       uint16
    Hr       uint16
    Feature  [3][20]int16
}

How to parse

  • 写回答

2条回答 默认 最新

  • dpvmjk0479 2019-09-06 04:08
    关注

    One way you can do is:

    decoder:=json.NewDecoder(input)
    decoder.UseNumber()
    var array []interface{}
    decoder.Decode(&array)
    heartBeat.Template=uint8(array[0].(json.Number).Int64())
    heartBeat.Index=uint32(array[2].(json.Number).Int64())
    ...
    feature:=array[5].([]interface{})
    heartBeat.Feature[0][0]=int16(feature[0].([]interface{})[0].(json.Number).Int64())
    

    Of course, you have to add error and bounds checking to the code.

    评论

报告相同问题?

悬赏问题

  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch