代码如下:
```
package main
import (
"encoding/json"
"fmt"
)
type MqttClientConfigEntry struct {
Broker string `json: "broker"`
ClientId string `json: "clientId"`
CleanSession bool `json: "cleanSession"`
KeepAliveInterval uint32 `json: "keepAliveInterval"`
Password string `json: "password"`
UserName string `json: "userName"`
PubTopic string `json: "pubTopic"`
SubTopic string `json: "subTopic"`
}
type MqttClientConfig struct {
E MqttClientConfigEntry `json: "MqttClient"`
}
const s = `{
"MqttClient": {
"broker": "8888888888888888888/",
"clientId": "11111111111111111",
"cleanSession": true,
"keepAliveInterval": 100,
"password": "2222222222222",
"userName": "3333333333333333",
"pubTopic": "9999999999",
"subTopic": "111111"
}
}`
func main() {
var mcc MqttClientConfig
err := json.Unmarshal([]byte(s), &mcc)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(mcc)
}
}
```
程序的目的是解析一个 json 字符串,返回的 error 为 nil,但 MqttClientConfig 对象没有任何数值填充进来:
输出如下
{{ false 0 }}
type MqttClientConfig struct {
MqttClient MqttClientConfigEntry `json: "MqttClient"`
}
这样声明,就可以了,你试试。
#5
更多评论