[英]How can I turn map[string]interface{} to different type of struct?
I'm calling an API which will return Json objects like this: 我正在调用一个API,它将返回如下Json对象:
{
name: "XXX"
type: "TYPE_1"
shared_fields: {...}
type_1_fields: {...}
..
type_2_fields: {...}
}
Based on different types, this object will have different kinds of fields, but these fields are certain for different types. 基于不同的类型,此对象将具有不同类型的字段,但是这些字段对于不同类型是确定的。 So, I unmarshal the Json string to map[string]interface{} to fetch the the different type but how can I turn these map[string]interface{} to a certain struct?
因此,我将Json字符串解组到map [string] interface {}以获取不同的类型,但是如何将这些map [string] interface {}转换为特定结构?
var f map[string]interface{}
err := json.Unmarshal(b, &f)
type := f["type"]
switch type {
case "type_1":
//initialize struct of type_1
case "type_2":
//initialize struct of type_2
}
For this sort of two-step json decoding you will probably want to check out json.RawMessage . 对于这种两步json解码,您可能需要检出json.RawMessage 。 It allows you to defer processing of parts of your json response.
它允许您推迟处理json响应的各个部分。 The example in the docs shows how.
文档中的示例显示了操作方法。
One way to do it would be to have a constructor function (one that starts with New…
) that takes a map as input parameter. 一种实现方法是拥有一个构造函数(一个以
New…
开头的函数),该函数将地图作为输入参数。
A second way, much slower in my opinion, would be to redo the unmarshalling to the right struct type. 在我看来,第二种方法要慢得多,那就是将重新编组为正确的struct类型。
If the types are different enough and you want to be lazy you can just try to decode it in each format: 如果类型足够不同并且您想偷懒,则可以尝试以每种格式对其进行解码:
f1 := type1{}
err := json.Unmarshal(b, &f1)
if err == nil {
return f1
}
f2 := type2{}
err := json.Unmarshal(b, &f2)
if err == nil {
return f2
}
...
If the objects are similar or you want to be less lazy, you could just decode the type and then do something: 如果对象相似或不想变得懒惰,则可以解码类型,然后执行以下操作:
type BasicInfo struct {
Type string `json:"type"`
}
f := BasicInfo{}
err := json.Unmarshal(b, &f)
switch f.Type {
case "type_1":
//initialize struct of type_1
case "type_2":
//initialize struct of type_2
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.