golang中的interface {}到[]字节转换

时间:2018-02-27 10:36:13

标签: json go

我正在尝试解组接口类型的数据。所以我需要将接口类型转换为[] byte并将其传递给unmarshall。 我试过了

  1. err := json.Unmarshal([]byte(kpi), &a) =>失败
  2. 我厌倦了通过使用将接口转换为字节  kpidata, res := kpi.([]byte) =>失败了,kpidata是nil
  3. 那么我们有什么方法可以转换它吗?

    示例:https://play.golang.org/p/5pqQ0DQ94Dp

2 个答案:

答案 0 :(得分:5)

基于库格尔提供的工作实例:

package main

import (
    "fmt"
)

func passInterface(v interface{}) {
    b, ok := v.(*[]byte)
    fmt.Println(ok)
    fmt.Println(b)
}

func main() {
    passInterface(&[]byte{0x00, 0x01, 0x02})
}

Play

如果你没有传递引用,它将基本相同:

Play

答案 1 :(得分:3)

在您的sample代码data中, JSON编码(简单来说就是 String ),因此您正在使用{ {1}}以错误的方式:

Unmarshal

The Go Playgroundthis: []string{"art", "football"}上尝试:

// Unmarshal parses the JSON-encoded data and stores the result
// in the value pointed to by v. If v is nil or not a pointer,
// Unmarshal returns an InvalidUnmarshalError.
func Unmarshal(data []byte, v interface{}) error

输出:

package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    // ********************* Marshal *********************
    u := map[string]interface{}{}
    u["name"] = "kish"
    u["age"] = 28
    u["work"] = "engine"
    //u["hobbies"] = []string{"art", "football"}
    u["hobbies"] = "art"

    b, err := json.Marshal(u)
    if err != nil {
        panic(err)
    }
    fmt.Println(string(b))

    // ********************* Unmarshal *********************
    var a interface{}
    err = json.Unmarshal(b, &a)
    if err != nil {
        fmt.Println("error:", err)
    }
    fmt.Println(a)
}

你想要解组,所以试试this简单的工作示例({"age":28,"hobbies":"art","name":"kish","work":"engine"} map[name:kish work:engine age:28 hobbies:art] ):

[]byte(kpi.(string)

输出:

package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    var kpi interface{} = st
    var a []Animal
    err := json.Unmarshal([]byte(kpi.(string)), &a)
    if err != nil {
        fmt.Println("error:", err)
    }
    fmt.Println(a)
}

type Animal struct {
    Name  string
    Order string
}

var st = `[
    {"Name": "Platypus", "Order": "Monotremata"},
    {"Name": "Quoll",    "Order": "Dasyuromorphia"}
]`

使用([{Platypus Monotremata} {Quoll Dasyuromorphia}] )工作example

[]byte(*kpi.(*string))

Marshal

package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    var kpi interface{} = &st
    var a []Animal
    err := json.Unmarshal([]byte(*kpi.(*string)), &a)
    if err != nil {
        fmt.Println("error:", err)
    }
    fmt.Println(a)
}

type Animal struct {
    Name  string
    Order string
}

var st = `[
    {"Name": "Platypus", "Order": "Monotremata"},
    {"Name": "Quoll",    "Order": "Dasyuromorphia"}
]`

输出:

package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    u := map[string]interface{}{}
    u["1"] = "one"
    b, err := json.Marshal(u)
    if err != nil {
        panic(err)
    }
    fmt.Println(string(b))
}

我希望这会有所帮助。