在程序中使用Json数据时,有时会根据type的类型不同,定义的data数据的json结构不同。
如:
{
"type":"File",
"object":{
"filename":"test"
}
}
{
"type":"Png",
"object":{
"width":1280,
"hight":1920
}
}
此时在解析json数据时,需要先解析出type的值,再根据type的值进行判断来解析object的数据。Golang提供了RawMessage来处理这种情况:
示例代码如下:
package main
import (
"encoding/json"
)
type UpLoadSomething struct {
Type string
Object interface{}
}
type File struct {
FileName string
}
type Png struct {
Width int
Hight int
}
func main() {
input :=
{
"type": "File",
"object": {
"filename": "for test"
}
}
var object json.RawMessage
ss := UpLoadSomething{
Object: &object,
}
if err := json.Unmarshal([]byte(input), &ss); err != nil {
panic(err)
}
switch ss.Type {
case "File":
var f File
if err := json.Unmarshal(object, &f); err != nil {
panic(err)
}
println(f.FileName)
case "Png":
var p Png
if err := json.Unmarshal(object, &p); err != nil {
panic(err)
}
println(p.Wide)
}
}
欢迎扫码关注公众号,更好的交流