json - 为什么不能将此数据正确解码到我的对象模型中?

标签 json go unmarshalling

我这里有一个(非)工作示例:https://play.golang.org/p/qaYhKvJ65J3

我不确定为什么会出现以下数据:

alertData := `{
    "Id": 0,
    "Version": 0,
    "OrgId": 1,
    "DashboardId": 61,
    "PanelId": 84,
    "Name": "{qa-dev}{stats-pipeline} Topology Message Age (aggregator) alert",
    "Message": "",
    "Severity": "",
    "State": "",
    "Handler": 1,
    "Silenced": false,
    "ExecutionError": "",
    "Frequency": 10,
    "EvalData": null,
    "NewStateDate": "0001-01-01T00:00:00Z",
    "PrevStateDate": "0001-01-01T00:00:00Z",
    "StateChanges": 0,
    "Created": "0001-01-01T00:00:00Z",
    "Updated": "0001-01-01T00:00:00Z",
    "Settings": {
        "conditions": [
            {
                "evaluator": {
                    "params": [
                        10000
                    ],
                    "type": "gt"
                },
                "operator": {
                    "type": "and"
                },
                "query": {
                    "datasourceId": 2,
                    "model": {
                        "hide": true,
                        "refCount": 0,
                        "refId": "C",
                        "textEditor": false
                    },
                    "params": [
                        "C",
                        "5m",
                        "now"
                    ]
                },
                "reducer": {
                    "params": [],
                    "type": "avg"
                },
                "type": "query"
            }
        ],
        "executionErrorState": "keep_state",
        "frequency": "10s",
        "handler": 1,
        "name": "{qa-dev}{stats-pipeline} Topology Message Age (aggregator) alert",
        "noDataState": "keep_state",
        "notifications": []
    }
}`

无法解码到以下对象模型中:

type Condition struct {
    Evaluator struct {
        Params []int  `json:"params"`
        Type   string `json:"type"`
    } `json:"evaluator"`
    Operator struct {
        Type string `json:"type"`
    } `json:"operator"`
    Query struct {
        Params []string `json:"params"`
    } `json:"query"`
    Reducer struct {
        Params []interface{} `json:"params"`
        Type   string        `json:"type"`
    } `json:"reducer"`
    Type string `json:"type"`
}

当我执行以下操作时:

condition := Condition{}
err := json.Unmarshal([]byte(alertData), &condition)

if err != nil {
    panic(err)
}

fmt.Printf("\n\n json object:::: %+v", condition)

我刚得到:json object:::::{Evaluator:{Params:[] Type:} Operator:{Type:} Query:{Params:[]} Reducer:{Params:[] Type: } 类型:

理想情况下,我能够将其解析为类似type Conditions []struct{ } 的内容,但我不确定您是否可以将模型定义为列表?

最佳答案

看起来您正在尝试访问嵌套在根“设置”属性下的“条件”属性。因此,您需要定义该根级类型和足够的字段来告诉解码器如何找到您的目标属性。因此,您只需要创建一个带有必要“设置/条件”字段的新“AlertData”类型。

例如 ( Go Playground ):

type AlertData struct {
  Settings struct {
    Conditions []Condition `json:"conditions"`
  }
}

func main() {
  alert := AlertData{}
  err := json.Unmarshal([]byte(alertData), &alert)

  if err != nil {
    panic(err)
  }

  fmt.Printf("OK: conditions=%#v\n", alert.Settings.Conditions)
  // OK: conditions=[]main.Condition{main.Condition{Evaluator:struct { Params []int "json:\"params\""; Type string "json:\"type\"" }{Params:[]int{10000}, Type:"gt"}, Operator:struct { Type string "json:\"type\"" }{Type:"and"}, Query:struct { Params []string "json:\"params\"" }{Params:[]string{"C", "5m", "now"}}, Reducer:struct { Params []interface {} "json:\"params\""; Type string "json:\"type\"" }{Params:[]interface {}{}, Type:"avg"}, Type:"query"}}
}

请注意,打印的列表包含如此多的类型信息,因为“条件”类型使用匿名结构作为字段类型。如果您要将它们提取到命名结构中,那么使用数据会更容易,例如:

type Condition struct {
  Evaluator Evaluator `json:"evaluator"`
  Operator  Operator  `json:"operator"`
  // ...
}

type Evaluator struct {
  Params []int  `json:"params"`
  Type   string `json:"type"`
}

type Operator struct {
  Type string `json:"type"`
}

//...
// OK: conditions=[]main.Condition{
//   main.Condition{
//     Evaluator:main.Evaluator{Params:[]int{10000}, Type:"gt"},
//     Operator:main.Operator{Type:"and"},
//     Query:main.Query{Params:[]string{"C", "5m", "now"}},
//     Reducer:main.Reducer{Params:[]interface {}{}, Type:"avg"},
//     Type:"query",
//   },
// }

Go Playground example here...

关于json - 为什么不能将此数据正确解码到我的对象模型中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52616855/

相关文章:

php - 读取和写入 SQL 数据库

javascript - 如何将序列化的 JSON 字符串包装在 'single quotes' 中

json - 构建一个 golang 结构来存储来自已解析的 JSON 文件的数据

java - 如何使用 JAXB 解码包含混合标签(具有属性,并且具有嵌套标签的内容值)的 XML 文件?

c# - 如何使用 JsonTextReader 两次

windows - 如何使用转义序列

go - 从Go程序访问AKS kubeconfig文件

loops - 在循环迭代器变量上使用 goroutines

android - ClassNotFoundException 解码时真的不知道为什么

javascript - 对象到 node.js 中的 json 字符串