Golang implements the conversion when the JSON type is uncertain

Time:2022-5-8

When converting JSON into a structure, we often encounter the situation that we cannot determine the type of a field. In go, you can use any type of interface to solve the problem.


// convert json to struct
// type uncertain
package main
import (
 "fmt"
 "encoding/json"
)
type Host struct {
 Id interface{}
 IdcId interface{}
}
func main() {
 b := []byte(`{"ID": 11, "IDCid": "1001"}`)
 m := Host{}
 err := json.Unmarshal(b, &m)
 if err != nil {
 fmt.Println("Umarshal failed:", err)
 return
 }
 fmt.Printf("m:%#v\n", m)
}

output:


m:main.Host{Id:11, IdcId:”1001”}}

Supplement: there are fields of uncertain type in gin bindjson structure

If there are fields with uncertain types in the structure, the corresponding types will be automatically stored according to the input after using interface {} and bindjson, such as


type student struct {
 Name string   `json:"name"`
 Info interface{} `json:"info"`
}

For example, the input of info

input

type

12

float64

“str”

string

{“str”:”value”}

map[string]interface {}

true

bool

The above is my personal experience. I hope I can give you a reference, and I hope you can support developpaer. If you have any mistakes or don’t consider completely, please don’t hesitate to comment.