在Go中解组JSON数组数组

时间:2017-02-21 21:06:31

标签: arrays json go struct

我想在go中解析一些json数据。数据如下所示:

  

{ “ID”: “someId”, “key_1”: “_1”, “key_2”: “_2”, “KEY_3”: “VALUE_3”, “点”:[[1487100466412 “50.032178”,“8.526018 ” 300,0.0,26,0],[1487100471563 “50.030869”, “8.525949”,300,0.0,38,0],[1487100475722 “50.028514”, “8.525959”,225,0.0,69,-900 ],[1487100480834 “50.025827”, “8.525793”,275,0.0,92,-262],...]}

我构建了一个go结构:

type SomeStruct struct {
   ID   string `json:"id"`
   Key1 string `json:"key_1"`
   Key2 string `json:"key_2"`
   Key3 string `json:"key_3"`
   Points []Point `json:"points"`
}

type Point struct {
   Timestamp int64 `json:"0"`
   Latitude float64 `json:"1,string"`
   Longitude float64 `json:"2,string"`
   Altitude int `json:"3"` 
   Value1 float64 `json:"4"`
   Value2 int `json:"5"`
   Value3 int `json:"6"`      
}

我解组json数据

var track SomeStruct
error := json.Unmarshal(data,&track)
if(error != nil){
    fmt.Printf("Error while parsing data: %s", error)
}
  

json:无法将数组解组为Point类型的Go值{someId value_1 value_2 value_3 [{0 0 0 0 0 0 0} {0 0 0 0 0 0 0} {0 0 0 0 0 0 0} ... ]}

所以第一个json键被正确解析,但我无法弄清楚如何获取点数据,这是一个数组数组。

generate struct也是这里的建议结构,除了我不使用嵌套结构但是使用单独的类型。使用建议的嵌套结构没有区别: JSON-to-Go

我需要为此实现我自己的Unmarshaller吗?

=======更新解决方案============

为Point结构实现UnmarshalJSON接口就足够了。 下面的示例不包含正确的错误处理,但它显示了方向。

Playground example

package main

import (
    "encoding/json"
    "fmt"
    "strconv"
)

type SomeStruct struct {
    ID     string  `json:"id"`
    Key1   string  `json:"key_1"`
    Key2   string  `json:"key_2"`
    Key3   string  `json:"key_3"`
    Points []Point `json:"points"`
}

type Point struct {
    Timestamp int64
    Latitude  float64
    Longitude float64
    Altitude  int
    Value1    float64
    Value2    int16
    Value3    int16
}

func (tp *Point) UnmarshalJSON(data []byte) error {
    var v []interface{}
    if err := json.Unmarshal(data, &v); err != nil {
        fmt.Printf("Error whilde decoding %v\n", err)
        return err
    }
    tp.Timestamp = int64(v[0].(float64))
    tp.Latitude, _ = strconv.ParseFloat(v[1].(string), 64)
    tp.Longitude, _ = strconv.ParseFloat(v[2].(string), 64)
    tp.Altitude = int(v[3].(float64))
    tp.Value1 = v[4].(float64)
    tp.Value2 = int16(v[5].(float64))
    tp.Value3 = int16(v[6].(float64))

    return nil
}

func main() {

    const data =    `{"id":"someId","key_1":"value_1","key_2":"value_2","key_3":"value_3","points":[[1487100466412,"50.032178","8.526018",300,0.0,26,0],[1487100471563,"50.030869","8.525949",300,0.0,38,0],[1487100475722,"50.028514","8.525959",225,0.0,69,-900],[1487100480834,"50.025827","8.525793",275,0.0,92,-262]]}`

var something SomeStruct
json.Unmarshal([]byte(data), &something)

fmt.Printf("%v", something)
}

2 个答案:

答案 0 :(得分:3)

JSON:

[
  {
    "type": "Car",
    "wheels": 4
  },
  {
    "type": "Motorcycle",
    "wheels": 2
  }
]

结构:

type Vehicle struct {
  Type   string
  Wheels int
}

解组官:

func TestVehicleUnmarshal(t *testing.T) {
    response := `[{"type": "Car","wheels": 4},{"type": "Motorcycle","wheels": 2}]`

    var vehicles []Vehicle
    json.Unmarshal([]byte(response), &vehicles)

    assert.IsType(t, Vehicle{}, vehicles[0])
    assert.EqualValues(t, "Car", vehicles[0].Type)
    assert.EqualValues(t, 4, vehicles[0].Wheels)
    assert.EqualValues(t, "Motorcycle", vehicles[1].Type)
    assert.EqualValues(t, 2, vehicles[1].Wheels)
}

https://play.golang.org/p/5SfDH-XZt9J

答案 1 :(得分:1)

  

我需要为此实现我自己的Unmarshaller吗?

您正在尝试将数组解组为结构(Point),这意味着您需要告诉JSON解组器数组值如何映射到结构值。

另请注意,Point定义中的代码不正确。 json标签引用了键名,但是数组没有键(在JavaScript中,它们可以被访问,就像它们一样,但这不是JavaScript)。换句话说,json:"0"仅在您的JSON看起来像{"0":123}时才有效。如果你实现自己的unmarshaler,你可以摆脱那些json标签。