簡體   English   中英

用golang解析Json文件,遇到問題“cannot unmarshal object into Go value of type”

[英]Parse a Json file with golang, encountering a problem “cannot unmarshal object into Go value of type”

我有一個 JSON 文件如下:

{
  "contracts": [
    {
      "name": "contract1",
      "funcs": [
        {
          "name": "func1",
          "callchain": ["parfunc1", "parfunc2", "parfuncN"],
          "stateFuncs": ["stafunc1", "stafunc2", "stafuncN"],
          "consOnInputs": ["param1>20", "param2<10", "param4+param5>80"]
        },

        {
          "name": "func2",
          "callchain": ["2parfunc1", "2parfunc2", "2parfunN"],
          "stateFuncs": ["2stafunc1", "2stafunc2", "2stafuncN"],
          "consOnInputs": ["param1>20", "param2<10", "param4+param5>80"]
      ]
    },

    {
      "name": "contract2",
      "funcs": [
        {
          "name": "func3",
          "callchain": ["parfunc5", "parfunc5", "parfuncN"],
          "stateFuncs": ["stafunc8", "stafunc8", "stafuncN"],
          "consOnInputs": ["param1>20", "param2<10", "param4+param5>80"]
        }
      ]
    }
  ]
}

I encounter the problem json: cannot unmarshal object into Go struct field ContractAll.contracts of type main.ContractInfo contracts: {[[] []]} with the following unmarshalled codes, where the json_content contains contents of the JSON file:

type FuncInfo struct {
    Name string `json:"name"`
    Callchain []string `json:"callchain"`
    StateFuncs []string `json:"stateFuncs"`
    ConsOnInputs []string `json:"consOnInputs"`
}

type ContractInfo []struct{
    Name string `json:"name"`
    Funcs []FuncInfo `json:"funcs"`
}

type ContractAll struct {
    Contracts []ContractInfo `json:"contracts"`
}

var contracts ContractAll
err = json.Unmarshal([]byte(json_content), &contracts)

我該如何解決這個問題?

您的結構與輸入不匹配。 你還需要一個:

type Contracts struct {
   Contracts []ContractInfo `json:"contracts"`
}

...
var contracts Contracts
err = json.Unmarshal([]byte(json_content), &contracts)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM