dongtangyi8962 2018-06-02 19:00
浏览 752
已采纳

Golang,使用[] byte类型的字段将bytes数组转换为struct

I need some help with unmarshaling. I have this example code:

package main

import (
    "encoding/json"
    "fmt"
)

type Obj struct {
    Id   string `json:"id"`
    Data []byte `json:"data"`
}

func main() {
    byt := []byte(`{"id":"someID","data":["str1","str2"]}`)

    var obj Obj
    if err := json.Unmarshal(byt, &obj); err != nil {
        panic(err)
    }

    fmt.Println(obj)
}

What I try to do here - convert bytes to the struct, where type of one field is []byte. The error I get:

panic: json: cannot unmarshal string into Go struct field Obj.data of type uint8

That's probably because parser already sees that "data" field is already a slice and tries to represent "str1" as some char bytecode (type uint8?).

How do I store the whole data value as one bytes array? Because I want to unmarshal the value to the slice of strings later. I don't include a slice of strings into struct because this type can change (array of strings, int, string, etc), I wish this to be universal.

  • 写回答

3条回答 默认 最新

  • doudong1117 2018-06-02 19:11
    关注

    My first recommendation would be for you to just use []string instead of []byte if you know the input type is going to be an array of strings.

    If data is going to be a JSON array with various types, then your best option is to use []interface{} instead - Go will happily unmarshal the JSON for you and you can perform checks at runtime to cast those into more specific typed variables on an as-needed basis.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?