golang类型转换。 结构接口

I am not used to golang.

When I requested, I got the below log.

I would like to parse the log and store into struct type.

Someone lets me know how to do?

Thanks in advance.

for example :

type ResultStruct struct{
    id int
    guid string
    name string
}

for k, v := range data {
    fmt.Print(v.id) fmt.Print(v.guid) fmt.Print(v.name)
}

[log]

data: [map[id:90001 guid:a name:test1] map[guid:b name:test2 id:90002] map[name:test3 id:90003 guid:c]]

[source]

response := httpClient.Do(request)
var data interface{}
rawdata, err := ioutil.ReadAll(response.body)
json.Unmarshal(rawdata, &data)
fmt.Println("data :", data)

You are getting an Array, Unmarshal it using the encoding/json package.

type ResultStruct struct {
    id int      `json:"id"`
    guid string `json:"guid"`
    name string `json:"name"`
}
type Result struct {
    Data []ResultStruct `json:"data"`
}

response := httpClient.Do(request)
var data Result
decErr := json.NewDecoder(response.body).Decode(&data)
fmt.Println(decErr, data)

This should Unmarshal the data into array.

It is a common mistake for new Go programmers.

Because of language design, json.Unmarshal can only marshal into exported fields.

Simply capitalize the first letter of each field name to export them. Optionally you may add field tags to tell json.Marshal what key-name to use. This is only needed if you are going to use json.Marshal.

type ResultStruct struct{
    Id   int    `json:"id"`
    Guid string `json:"guid"`
    Name string `json:"name"`
}

To quote the encoding/json package:

To unmarshal JSON into a struct, Unmarshal matches incoming object keys to the keys used by Marshal (either the struct field name or its tag), preferring an exact match but also accepting a case-insensitive match. Unmarshal will only set exported fields of the struct.