2018-06-02 19:00
浏览 692

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

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

package main

import (

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 {


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 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条回答 默认 最新

相关推荐 更多相似问题