简体   繁体   English

在字节数组上使用 json.Unmarshal() 时出现问题

[英]Problem when using json.Unmarshal() on a byte array

I have a struct for image data我有一个图像数据结构

type ImageData struct {
    Name string
    Data []byte
}

The Data field is an image converted to bytes.数据字段是转换为字节的图像。

I have jsonImages like [{"Data":<many-many bytes>, "Name":"abracadabra"}] and var imagesData []ImageData .我有jsonImages[{"Data":<many-many bytes>, "Name":"abracadabra"}]var imagesData []ImageData And when I try to use json.Unmarshal([]byte(jsonImages), &imagesData) as a result of fmt.Println(imagesData) I receive [{abracadabra []}] .当我尝试使用json.Unmarshal([]byte(jsonImages), &imagesData)作为fmt.Println(imagesData)的结果时,我收到[{abracadabra []}] The Data field is empty.数据字段为空。 What am I doing wrong?我究竟做错了什么? Thanks for any help!谢谢你的帮助!

I tried replicating the scenario with below snippet It worked fine.Is this the one you are trying:我尝试用下面的代码片段复制场景它工作正常。这是您正在尝试的场景吗:

package main

import (
    "encoding/json"
    "fmt"
)

type Imgdta struct {
    Name string
    Dta  []byte
}

func main() {
    var Imgdta1 Imgdta
    var Imgdta2 Imgdta
    Imgdta1.Dta = []byte("asfafalsffa")
    Imgdta1.Name = "asnakakad"
    imgjson, _ := json.Marshal(Imgdta1)
    fmt.Println("Input Json:-", string(imgjson))
    json.Unmarshal((imgjson), &Imgdta2)
    fmt.Println((Imgdta2))
}

... Result: ... 结果:

Input Json:- {"Name":"asnakakad","Dta":"YXNmYWZhbHNmZmE="}
{asnakakad [97 115 102 97 102 97 108 115 102 102 97]}

URL - https://play.golang.org/p/LQNwLqDTvt5网址 - https://play.golang.org/p/LQNwLqDTvt5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM