用json读取json数组.新解码器



如何使用json将json数组(json文件中的命名列表(获取到列表中。新解码器?我的结构如下:

type Config struct {
Data1 struct {
Host string `json:"host"`
Port string `json:"port"`
} `json:"data1"`
Data2 struct {
Host string `json:"host"`
Port string `json:"port"`
} `json:"data2"`
List struct {
Items []string
} `json:"list"`
}

我是这样分析的:

jsonParser := json.NewDecoder(configFile)
jsonParser.Decode(&config)

我的config.json看起来像这个

{
"data1": {
"host": "10.10.20.20",
"port": "1234"
},
"data2": {
"host": "10.10.30.30",
"port": "5678"
},
"list": [
"item 1",
"item 2",
"item 3",
"item 4"
]
}

当字段有名称时很容易,但我还没有弄清楚如何从列表中获取信息。。。

我找到了解决问题的方法。这是代码:

package main
import (
"encoding/json"
"fmt"
"strings"
)
type ConfigWithoutList struct {
Data1 struct {
Host string `json:"host"`
Port string `json:"port"`
} `json:"data1"`
Data2 struct {
Host string `json:"host"`
Port string `json:"port"`
} `json:"data2"`
}
type Config struct {
ConfigWithoutList
List struct {
Items []string
} `json:"list"`
}
func (u *Config) UnmarshalJSON(data []byte) error {
aux := struct {
List []string `json:"list"`
ConfigWithoutList
}{}
if err := json.Unmarshal(data, &aux); err != nil {
return err
}
u.List = struct {
Items []string
}{
Items: aux.List,
}
return nil
}
func main() {
const jsonStream = `{
"data1": {
"host": "10.10.20.20",
"port": "1234"
},
"data2": {
"host": "10.10.30.30",
"port": "5678"
},
"list": [
"item 1",
"item 2",
"item 3",
"item 4"
]
}
`
config := Config{}
jsonParser := json.NewDecoder(strings.NewReader(jsonStream))
jsonParser.Decode(&config)
fmt.Println(config.List) // output => {[item 1 item 2 item 3 item 4]}
}

最新更新