Golang parse json data according to type RawMessage

When using Json data in the program, sometimes depending on the type of different type, different data json data structure definition.
Such as:

{
    "type":"File",
    "object":{
        "filename":"test"
    }
}
{
    "type":"Png",
    "object":{
        "width":1280,
        "hight":1920
    }
}

At this time, when parsing json data, the need to resolve the value of the type, then the value is determined according to the type of object to parse the data. Golang RawMessage provided to handle this situation:
the following sample code:

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)
    }
}

Welcome to sweep the code number of public attention, better communication
Welcome to sweep the code number of public attention, better communication

Published 115 original articles · won praise 67 · Views 100,000 +

Guess you like

Origin blog.csdn.net/meifannao789456/article/details/98059950