如何解码没有字段名称的字符串和整数 slice ?

这是我尝试解码的远程API的输出:

[["9BC67ACD", "example1", "example1.co.uk", "2018-08-06 08:46:44", "2018-08-06 08:46:44", "2018-08-06 08:46:44", "FINISHED", 1], ["B339CBA2", "example2", "example2.co.uk", "2018-08-06 08:38:25", "2018-08-06 08:38:24", "2018-08-06 08:38:27", "FINISHED", 1]]

做完后我得到了一个字节
rBody, err := ioutil.ReadAll(r.Body)

我可以使用带有[][]interface{}的json解码器对此进行解码吗?

最佳答案

您的问题:-



是的,您可以解码JSON输出没有问题。这是JSON数组。

[["9BC67ACD", "example1", "example1.co.uk", "2018-08-06 08:46:44", "2018-08-06 08:46:44", "2018-08-06 08:46:44", "FINISHED", 1], ["B339CBA2", "example2", "example2.co.uk", "2018-08-06 08:38:25", "2018-08-06 08:38:24", "2018-08-06 08:38:27", "FINISHED", 1]]

或者,您可以将JSON解码到接口(interface){}中。但是在两种情况下,您都需要类型断言来获取接口(interface)的基础值。
package main

import (
    "fmt"
    "encoding/json"
)

var jsonBytes string = `[["9BC67ACD", "example1", "example1.co.uk", "2018-08-06 08:46:44", "2018-08-06 08:46:44", "2018-08-06 08:46:44", "FINISHED", 1], ["B339CBA2", "example2", "example2.co.uk", "2018-08-06 08:38:25", "2018-08-06 08:38:24", "2018-08-06 08:38:27", "FINISHED", 1]]`

func main() {
    var result interface{}
    if err := json.Unmarshal([]byte(jsonBytes), &result); err != nil{
        fmt.Println(err)
    }
    fetchValue(result) // This function recursively get the underlying value of an interface.
}

func fetchValue(value interface{}) {
    switch value.(type) {
    case string:
        fmt.Printf("%v is an string \n ", value.(string))
    case bool:
        fmt.Printf("%v is bool \n ", value.(bool))
    case float64:
        fmt.Printf("%v is float64 \n ", value.(float64))
    case []interface{}:
        fmt.Printf("%v is a slice of interface \n ", value)
        for _, v := range value.([]interface{}) {
            fetchValue(v)
        }
    case map[string]interface{}:
        fmt.Printf("%v is a map \n ", value)
        for _, v := range value.(map[string]interface{}) {
            fetchValue(v)
        }
    default:
        fmt.Printf("%v is unknown \n ", value)
    }
}

Playground example

关于json - 解码字符串和整数 slice ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51704860/

10-16 07:03