解码自定义值映射

huangapple go评论81阅读模式
英文:

unmarshal custom value map

问题

我已经为地图创建了一个自定义类型。我想将一个数组JSON响应反序列化为该地图。地图的键值在每次接收响应时都会发生变化。我遇到的问题是反序列化函数无法正确映射到自定义值。

    type id map[string]yp

    type yp struct {
	    f1		string				
	    f2		int		
    }	

    func main() {
        data := []byte("[{\"unique1\":{\"f1\":\"1\",\"f2\":\"2\"}},{\"unique2\":{\"f1\":\"4\",\"f2\":\"7\"}}]")
        var i []id
        json.Unmarshal(data, &i)
        fmt.Printf("%v", i)
    }
英文:

I have created a custom type for a map. I would like to unmarshal an array
json response into the map. The key value of the map changes each time the response is received. The issue I have is the unmarshal function does not map correctly to the custom values.

    type id map[string]yp

    type yp struct {
	    f1		string				
	    f2		int		
    }	

    func main() {
        data := []byte("[{\"unique1\":{\"f1\":\"1\",\"f2\":\"2\"}},{\"unique2\":{\"f1\":\"4\",\"f2\":\"7\"}}]")
        var i []id
        json.Unmarshal(data,&i)
        fmt.Printf("%v",i)
    }

答案1

得分: 1

由于f2的源值是字符串,你需要添加一个字段标签:

package main

import (
   "encoding/json"
   "fmt"
)

var data = []byte(`
[
   {
      "unique1": {"f1": "1", "f2": "2"}
   }, {
      "unique2": {"f1": "4", "f2": "7"}
   }
]
`)

func main() {
   var ids []map[string]struct {
      F1 string              
      F2 int `json:"f2,string"`
   }
   json.Unmarshal(data, &ids)
   // [map[unique1:{F1:1 F2:2}] map[unique2:{F1:4 F2:7}]]
   fmt.Printf("%+v\n", ids)
}
英文:

Since the source value for f2 is string, you need to add a field tag:

package main

import (
   "encoding/json"
   "fmt"
)

var data = []byte(`
[
   {
      "unique1": {"f1": "1", "f2": "2"}
   }, {
      "unique2": {"f1": "4", "f2": "7"}
   }
]
`)

func main() {
   var ids []map[string]struct {
      F1 string              
      F2 int `json:"f2,string"`
   }
   json.Unmarshal(data, &ids)
   // [map[unique1:{F1:1 F2:2}] map[unique2:{F1:4 F2:7}]]
   fmt.Printf("%+v\n", ids)
}

huangapple
  • 本文由 发表于 2021年9月2日 02:15:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/69018789.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定