如何将动态JSON响应映射到GO结构? [重复]

This question already has an answer here:

I am new to golang and trying to parse some response from a web service, and the response looks like:

[
  {
    "Data": {
      "KeyA": 1,
      "KeyB": 2
    },
    "Type": 0
  },
  {
    "Data": {
      "KeyX": "ValueX",
      "KeyY": 999
    },
    "Type": 1
  },
  {
    "Data": {
      "Val": 123,
      "Id": "999",
      "Cnt": 100
    },
    "Type": 2
  }
]

You can see that each element has a Key "Data" and "Type" (Must), but with different 'Type' comes the different 'Data' field.

Could you please suggest a efficiency way to construct this kind of response to Golang structure?

Thanks.

</div>

This should work for you

type Test []struct {
    Data map[string]interface{} `json:"Data"`
    Type int `json:"Type"`
}

since the only variable keys and values are in Data, make that a map instead and look for the keys inside based on the type received