duandong7980 2015-02-11 21:19
浏览 11
已采纳

Go-奇怪的JSON连字符解组错误

I am having a very strange error while working with a json string. The problem was first introduced when I added a key-value pair of strings to the json input, which was "DeviceIdentifier": "device-id". I pared down my code to the minimum necessary to display the error. The error disappears when I change pretty much anything about the data in that key-value pair, which seems very strange to me. I can just use other keys to circumvent the error, but it seems like there is something I am missing here. Either that or there would seem to be something wrong with the library function... Any ideas?

package main

import (
    "encoding/json"
    "fmt"
)

type S struct {
    Name            string
    DeviceIdentifier []byte
}

func main() {
    var s S

    data := []byte(`{"Name": "test", "DeviceIdentifier": "device-id"}`)

    if err := json.Unmarshal(data, &s); err != nil {
        fmt.Println(err.Error())
    }
}

Go playground link: http://play.golang.org/p/huXuaokGik

Json package documentation: http://golang.org/pkg/encoding/json/

UPDATE

I just discovered that the encoding succeeds when the value string has a length that is divisible by 4, e.g. abcd and abcdefgh work, while abcde and abcdefg` do not.

Now that I know what base64 strings are the error makes a lot of sense. References here:

Wikipedia: http://en.wikipedia.org/wiki/Base64

Conversion tool: http://www.string-functions.com/base64encode.aspx

  • 写回答

2条回答 默认 最新

  • duanre4421 2015-02-11 21:28
    关注

    from the json package documentation :

    Array and slice values encode as JSON arrays, except that []byte encodes as a base64-encoded string, and a nil slice encodes as the null JSON object.

    so if you change your structure to DeviceIdentifier string it will work

    Go Playground

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

报告相同问题?

悬赏问题

  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行