我必须在go中格式化一个json,我有一些问题。我在java中使用的字符串文字如下:
String jsonString= "{\"stream\":\"temperatura2\",\r\n" +
"\"sensor\":\"ec6c613a-66b4-4584-fb37-5f7cac130f7d\",\r\n" +
"\"values\":[{\"time\":\"2019-03-10T11:30:00Z\",\"components\":{\"alfanum\":\"99.0\"}}]}\r\n";所以我创建了这个结构:
type YuccaDataStream struct {
Stream string `json:"stream"`
Sensor string `json:"sensor"`
Values []struct {
Time time.Time `json:"time"`
Components struct {
Alfanum string `json:"alfanum"`
} `json:"components"`
} `json:"values"`
}这个结构正确吗?我不知道如何创建该结构的实例并用当前时间填充它。
发布于 2019-11-29 05:14:33
这样如何:
package main
import (
"fmt"
"time"
"encoding/json"
)
type YuccaDataStream struct {
Stream string `json:"stream"`
Sensor string `json:"sensor"`
Values []Value `json:"values"`
}
type Value struct {
Time time.Time `json:"time"`
Components `json:"components"`
}
type Components struct {
Alfanum string `json:"alfanum"`
}
func main() {
data := []byte(`{"stream": "temperatura2","sensor": "ec6c613a-66b4-4584-fb37-5f7cac130f7d","values": [{"time": "2019-03-10T11:30:00Z","components": {"alfanum": "99.0"}}]}`)
var unmarshaled YuccaDataStream
err := json.Unmarshal(data, &unmarshaled)
if err != nil {
panic(err)
}
fmt.Printf("%v",unmarshaled)
}https://stackoverflow.com/questions/59095736
复制相似问题