json 接口{}到[]字节在golang中的转换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49006594/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 19:06:17  来源:igfitidea点击:

interface{} to []byte conversion in golang

jsongo

提问by kish

I am trying to unmarshal a data which is of type interface. So I need to convert the interface type to []byte and pass it to unmarshall. i tried

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

  1. err := json.Unmarshal([]byte(kpi), &a)=> failed
  2. i tired to convert the interface to byte by using kpidata, res := kpi.([]byte)=> failed, kpidata is nil
  1. err := json.Unmarshal([]byte(kpi), &a)=> 失败
  2. 我厌倦了使用kpidata, res := kpi.([]byte)=>将接口转换为字节 失败,kpidata 为零

So is there any way we can convert it?

那么有什么方法可以转换它吗?

Example: https://play.golang.org/p/5pqQ0DQ94Dp

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

回答by matthias krull

Working example based on the one provided by Kugel:

基于 Kugel 提供的工作示例:

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

If you do not pass references, it will work basically the same:

如果你不传递引用,它的工作原理基本相同:

Play

回答by wasmup

In your samplecode datashould be JSON-encoded(in simple word String) so you are using Unmarshalin a wrong way:

在您的示例代码中data应该是JSON 编码的(在简单的单词String 中),所以您Unmarshal以错误的方式使用:

// 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
// 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

Try it on The Go Playgroundand this: []string{"art", "football"}:

尝试在旅途游乐场这样的:[]string{"art", "football"}

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

output:

输出:

{"age":28,"hobbies":"art","name":"kish","work":"engine"}
map[name:kish work:engine age:28 hobbies:art]


You want to Unmarshalit, so try thissimple working example ([]byte(kpi.(string)):

你想解组它,所以试试这个简单的工作示例 ( []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"}
]`

output:

输出:

[{Platypus Monotremata} {Quoll Dasyuromorphia}]


Working exampleusing ([]byte(*kpi.(*string))):

使用 ( ) 的工作示例[]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"}
]`


Marshal:

元帅

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

output:

输出:

{"1":"one"}

I hope this helps.

我希望这有帮助。