的JSON字符串的问题是这样的:如何解析Go中的这个JSON字符串?
{
"development":{
"connector":[
{"id":"connector-server-1", "host":"127.0.0.1", "port":4050, "wsPort":3050},
{"id":"connector-server-2", "host":"127.0.0.1", "port":4051, "wsPort":3051},
{"id":"connector-server-3", "host":"127.0.0.1", "port":4052, "wsPort":3052}
],
"chat":[
{"id":"chat-server-1", "host":"127.0.0.1", "port":6050},
{"id":"chat-server-2", "host":"127.0.0.1", "port":6051},
{"id":"chat-server-3", "host":"127.0.0.1", "port":6052}
],
"gate":[
{"id": "gate-server-1", "host": "127.0.0.1", "wsPort": 3014}
]
},
"production":{
"connector":[
{"id":"connector-server-1", "host":"127.0.0.1", "port":4050, "wsPort":3050},
{"id":"connector-server-2", "host":"127.0.0.1", "port":4051, "wsPort":3051},
{"id":"connector-server-3", "host":"127.0.0.1", "port":4052, "wsPort":3052}
],
"chat":[
{"id":"chat-server-1", "host":"127.0.0.1", "port":6050},
{"id":"chat-server-2", "host":"127.0.0.1", "port":6051},
{"id":"chat-server-3", "host":"127.0.0.1", "port":6052}
],
"gate":[
{"id": "gate-server-1", "host": "127.0.0.1", "wsPort": 3014}
]
}
}
,我想用代码来解析这样的:
package config
import(
"sync"
"io/ioutil"
"encoding/json"
"errors"
"log"
)
type Service struct {
Id string `json:"id"`
Host string `json:"host"`
Port uint `json:"port"`
QueryPort uint `json:"queryPort"`
WsPort uint `json:"wsPort"`
ServiceType string
}
type Config struct {
Services []Service
Master Service
Mutex sync.RWMutex
}
func LoadServers(filepath, env string) (*Config, error) {
// 读取文件
content, err := ioutil.ReadFile(filepath)
if err != nil {
return nil, err
}
configs := make(map[string]map[string][]Service, 0)
err = json.Unmarshal(content, configs)
if err != nil {
return nil, err
}
}
我希望我的代码,这JSON字符串解析到一个map[string]map[string][]Service
。
,但它显示了错误:
json: Unmarshal(non-pointer map[string]map[string][]config.Service)
你看过类型解码器的例子吗http://golang.org/pkg/encoding/json/ –
我看看这篇文章,但我认为我的例子中的diffucutity是我想用map来解析json而不是对象。 – jianfeng