美文网首页
Json RawMessage

Json RawMessage

作者: kker | 来源:发表于2016-12-19 18:42 被阅读2450次

    在程序中使用Json时,有时某个字段其结构是根据其他字段(比如有个类型含义的字段)决定的,这个时候在解析时,需要先解析一部分,进行判断后,再解析出合适的Json结构。这时就需要用到Golang Json包的RawMessage这个对象。

    示例代码如下:

    package main
    
    import (
        "encoding/json"
    )
    
    type UpLoadSomething struct {
        Type   string
        Object interface{}
    }
    
    type File struct {
        FileName string
    }
    
    type Png struct {
        Wide  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)
        }
    }
    

    相关文章

      网友评论

          本文标题:Json RawMessage

          本文链接:https://www.haomeiwen.com/subject/bpitvttx.html