将JSON解封为Map的Struct



我有下面的程序。我需要将JSON数据转换为对象类型缓存,其中包含map[string]字符串类型的单个字段。我在初始化map和解组JSON时做错了一些事情,但无法识别语法问题。

注意:为了方便起见,我已经编组了数据,以便有样例JSON数据。

package main
import (
"fmt"
"encoding/json"
"strconv"
)
const data = `{"Mode":{"ID-1":"ON","ID-2":"OFF","ID-3":"ON"}}`
type Cache struct {
Mode map[string]string `json:"Mode"`
}
func main() {
jsonData, _ := json.Marshal(data)
fmt.Println(strconv.Unquote(string(jsonData)))
var c Cache
c.Mode = make(map[string]string) //I want to initialise map so that I can store data in next step, but this is wrong I know
c.Mode["ID-4"] = "ON" //Want to store data like this

json.Unmarshal(jsonData, &c) 
fmt.Println(c) //I am getting output as nil map i.e. {map[]}
for k, v := range c.Mode {
fmt.Println(k, v) //I am getting NO output i.e. blank
}
}

这是你的代码修复https://play.golang.org/p/5ftaiz_Q5wl(附加吹的副本)

package main
import (
"encoding/json"
"fmt"
"log"
)
const data = `{"Mode":{"ID-1":"ON","ID-2":"OFF","ID-3":"ON"}}`
type Cache struct {
Mode map[string]string `json:"Mode"`
}
func main() {
c := Cache{}
err := json.Unmarshal([]byte(data), &c)
if err != nil {
log.Println(err)
}
c.Mode["ID-4"] = "ON" //Want to store data like this
fmt.Println(c) 
for k, v := range c.Mode {
fmt.Println(k, v) 
}
}

输出如下:

{map[ID-1:ON ID-2:OFF ID-3:ON ID-4:ON]}
ID-2 OFF
ID-3 ON
ID-4 ON
ID-1 ON

相关内容

  • 没有找到相关文章

最新更新