尝试在Golang 1.12中解组JSON字节数组

时间:2019-06-21 19:52:47

标签: json go

我得到一个json字节数组,只是尝试将其解编为结构以供以后使用。

type Event struct {
    category  string `json:"category"`
    service   string `json:"service"`
    timestamp string `json:"timestamp"`
    value     string `json:"value"`
}
ba := []byte(`
    {
      "category": "category1",
      "service" : "service1",
      "timestamp": "06-21-2019T10:08:00",
      "value": "5"
    }`)
var event Event
err := json.Unmarshal(ba, &event)
if err != nil {
    log.Panicln(err)
}
log.Printf("%+v", event)

我期望:

2019/06/21 12:21:13 {category:category1 service:service1时间戳:06-21-2019T10:08:00值:5}

但是我却得到:

2019/06/21 12:21:13 {类别:服务:时间戳:值:}

1 个答案:

答案 0 :(得分:0)

如果将struct字段的小写首字母更改为大写,它将按预期工作。

type Event struct {
    Category  string `json:"category"` <-- // uppercase first letter means the field is exported (which means accessible to other packages, like encoding/json which will marshal the data into a struct)
    Service   string `json:"service"`
    Timestamp string `json:"timestamp"`
    Value     string `json:"value"`
}

运行

package main

import (
    "encoding/json"
    "log"
)

type Event struct {
    Category  string `json:"category"`
    Service   string `json:"service"`
    Timestamp string `json:"timestamp"`
    Value     string `json:"value"`
}

func main() {

    ba := []byte(`
        {
          "category": "category1",
          "service" : "service1",
          "timestamp": "06-21-2019T10:08:00",
          "value": "5"
        }`)
    var event Event
    err := json.Unmarshal(ba, &event)
    if err != nil {
        log.Panicln(err)
    }
    log.Printf("%+v", event)

}

给我结果

2019/06/21 13:03:09 {Category:category1 Service:service1 Timestamp:06-21-2019T10:08:00 Value:5}