繁体   English   中英

JSON 解组 Go 中的有符号整数数组

[英]JSON unmarshal array of signed integers in Go

我正在尝试将 JSON 从整数数组解组为 Go 中的字节片。

问题是我们只能在 JSON 中的数组包含正整数时执行此操作,因为它将在 Go 中被识别为 uint8。 当数组包含负整数时它不起作用。

例如:

  • 这个数组可以工作:[1, 2, 3, 4, 5]
  • 这个数组不起作用:[-14, 2, 3, 4, 5](-14 是负数)

这是我收到的错误消息

Cannot unmarshal config file; err= json: cannot unmarshal number -14 int to Go struct field <struct_field> of type uint8

有什么办法可以将 JSON 将负整数解组为 Go 中的字节片吗?

有什么办法可以将 JSON 将负整数解组为 Go 中的字节片吗?

不,因为负数超出了字节值的有效范围,就像任何大于 255 的数字一样。

谢谢大家的回答。

我找到了解决方案:由于我想要一个字节数组并且字节不能保存有符号整数,我可以做的是首先在 JSON 离线输入中将有符号整数转换为无符号整数,然后我可以对新的无符号数组进行 JSON 解组。

游乐场链接: https://play.golang.org/p/Th2DC9AGEEs

参考代码:

package main

import (
    "fmt"
)

func main() {
    arr := []int8{-14,1,2,3,4}
    var bytes []byte
    for _, val := range arr {
        bytes = append(bytes, convertToByte(val))
    }
    fmt.Println(bytes) // will print [242 1 2 3 4]
}

func convertToByte(value int8) byte {
    return byte(value)
}

暂无
暂无

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

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