自定义json解析处理不固定类型问题

Go语言本身是强类型的,处理一些弱类型语言的json时会遇到相同的字段,类型是不固定的这种情况,字段定义为interface{}挨个去解析可以解决这个问题,但随着数据量大了之后,嵌套格式越深,这将是一个大坑

[
    {
        "test": 1
    },
    {
        "test":  true
    }
]

在上面这段json里,type字段的值有传int类型的,有传bool类型的。
如果只是判断是与否,会定义为:

type Feature struct {
    Test bool `json:"test"`
}

假定现在就用这种结构体去解析Json:

const featuresText = `
[
    {
        "test": 1
    },
    {
        "test": true
    }
]`

func main() {
    var features []Feature
    e := json.Unmarshal([]byte(featuresText), &features)
    log.Printf("features: %#v,\nerror: %v", features, e)
}

会有错误信息输出:

features: []example.Feature{example.Feature{Test:false}, example.Feature{Test:true}},
error: json: cannot unmarshal number into Go struct field Feature.test of type bool

我们可以通过实现自定义Json解析来解决这个问题:

type Feature struct {
    Test bool `json:"test"`
}

// 定义一个字段类型为interface类型的Feature,再使用switch type来解决类型的问题
type TempFeature struct {
    Test interface{} `json:"test"` // 数字或布尔类型
}

// 自定义Feature Json解码
func (f *Feature) UnmarshalJSON(b []byte) (e error) {
    var temp TempFeature
    e = json.Unmarshal(b, &temp)
    if e != nil {
        return
    }
    // 判断类型
    switch v := temp.Test.(type) {
    case bool:
        f.Test = v
    case float64:
        f.Test = v > 0
    }
    return nil
}

执行之前的main方法,输出结果:

[]example.Feature{example.Feature{Test:true}, example.Feature{Test:true}},
error: <nil>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 世有妓,必有善者,名之善妓者,善通擅。 她把玩手中的那根红塔,已经有一会儿了,烟嘴几次被唾液沾湿,却始终没有点燃。...
    bjuu阅读 979评论 5 1
  • 米米是一只可爱的小老鼠,在鼠界可以说是大名鼎鼎啦!因为世界闻名的米老鼠就是他的亲哥哥,有这样一个哥哥,他自然也会倍...
    山里孩子爱大山阅读 655评论 20 13
  • 前言今天做的题中第二道题目是一道很好的题目,我的解法时间复杂度很差,可以根据类似自动机的思路改善复杂度。 136 ...
    Songger阅读 278评论 0 1
  • 这是刚刚在腾讯新闻上看到的问答。原文如下: 电视剧中的一段剧情令我感悟颇深:一个离婚妈妈为了不让儿子受欺负没有选择...
    岁月静好1阅读 789评论 0 1