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

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

报告相同问题?

悬赏问题

  • ¥15 算法题:数的划分,用记忆化DFS做WA求调
  • ¥15 chatglm-6b应用到django项目中,模型加载失败
  • ¥15 武汉岩海低应变分析软件,导数据库里不显示波形图
  • ¥15 CreateBitmapFromWicBitmap内存释放问题。
  • ¥30 win c++ socket
  • ¥30 CanMv K210开发板实现功能
  • ¥15 C# datagridview 栏位进度
  • ¥15 vue3页面el-table页面数据过多
  • ¥100 vue3中融入gRPC-web
  • ¥15 kali环境运行volatility分析android内存文件,缺profile