如何正确地反序列化不同类型的数组?

14
只要我有键值对,反序列化就很简单,但我如何反序列化一个不同类型的数组,其顺序也不确定?单个元素已经被定义并且已知,但是它们的顺序却不确定。我无法想出更好的解决方案。我是否应该尝试对所有元素进行尝试和错误处理?是否有某种联合类型可以为我完成这项工作? playground版本
package main

import (
    "encoding/json"
    "fmt"
)

var my_json string = `{
    "an_array":[
        "with_a string",
        {
            "and":"some_more",
            "different":["nested", "types"]
        }
    ]
}`

type MyInner struct {
    And     string
    Different   []string
}

type MyJSON struct {
    An_array []json.RawMessage
}

func main() {
    var my_json_test MyJSON

    e := json.Unmarshal([]byte(my_json), &my_json_test)
    if e != nil {
        fmt.Println(e)
    } else {
        for index, value := range my_json_test.An_array {
            fmt.Println("index: ", index)
            fmt.Println("value: ", string(value))
        }
        var my_inner MyInner
        err := json.Unmarshal(my_json_test.An_array[1], &my_inner)
        if err != nil {
            fmt.Println(err)
        } else {
            fmt.Println("inner structure: ", my_inner)
        }
    }
}
1个回答

22
Go官方博客有一篇关于 encoding/json 的好文章:JSON and GO。可以将 "任意数据解码" 成为一个 interface{},并使用类型断言动态确定类型。
您的代码可能可以修改为以下内容:
package main

import (
    "encoding/json"
    "fmt"
)

var my_json string = `{
    "an_array":[
    "with_a string",
    {
        "and":"some_more",
        "different":["nested", "types"]
    }
    ]
}`

func WTHisThisJSON(f interface{}) {
    switch vf := f.(type) {
    case map[string]interface{}:
        fmt.Println("is a map:")
        for k, v := range vf {
            switch vv := v.(type) {
            case string:
                fmt.Printf("%v: is string - %q\n", k, vv)
            case int:
                fmt.Printf("%v: is int - %q\n", k, vv)
            default:
                fmt.Printf("%v: ", k)
                WTHisThisJSON(v)
            }

        }
    case []interface{}:
        fmt.Println("is an array:")
        for k, v := range vf {
            switch vv := v.(type) {
            case string:
                fmt.Printf("%v: is string - %q\n", k, vv)
            case int:
                fmt.Printf("%v: is int - %q\n", k, vv)
            default:
                fmt.Printf("%v: ", k)
                WTHisThisJSON(v)
            }

        }
    }
}

func main() {

    fmt.Println("JSON:\n", my_json, "\n")

    var f interface{}
    err := json.Unmarshal([]byte(my_json), &f)
    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Printf("JSON: ")
        WTHisThisJSON(f)
    }
}

它的输出如下:
JSON:
 {
    "an_array":[
    "with_a string",
    {
        "and":"some_more",
        "different":["nested", "types"]
    }
    ]
} 

JSON: is a map:
an_array: is an array:
0: is string - "with_a string"
1: is a map:
and: is string - "some_more"
different: is an array:
0: is string - "nested"
1: is string - "types"

这还不完整,但它展示了它将如何工作。


1
我这边缺失的部分是type assertion - matthias krull

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接