简体   繁体   English

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

[英]JSON unmarshal array of signed integers in Go

I am trying to unmarshal JSON from an array of integers into a byte slice in Go.我正在尝试将 JSON 从整数数组解组为 Go 中的字节片。

The problem is we can do this only when the array in JSON contains positive integers as it will be recognized as uint8 in Go.问题是我们只能在 JSON 中的数组包含正整数时执行此操作,因为它将在 Go 中被识别为 uint8。 It doesn't work when the array contains negative integers.当数组包含负整数时它不起作用。

For example:例如:

  • this array will work: [1, 2, 3, 4, 5]这个数组可以工作:[1, 2, 3, 4, 5]
  • this array will not work: [-14, 2, 3, 4, 5] (-14 is negative)这个数组不起作用:[-14, 2, 3, 4, 5](-14 是负数)

This is the error message that I received这是我收到的错误消息

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

Is there any way I can do JSON unmarshal array with negative integers into a byte slice in Go?有什么办法可以将 JSON 将负整数解组为 Go 中的字节片吗?

Is there any way I can do JSON unmarshal array with negative integers into a byte slice in Go?有什么办法可以将 JSON 将负整数解组为 Go 中的字节片吗?

No, because negative numbers are outside of the valid range of byte values , just as any number greater than 255 is.不,因为负数超出了字节值的有效范围,就像任何大于 255 的数字一样。

Thank you all for the answers.谢谢大家的回答。

I found the solution: Since I want a byte array and byte cannot hold signed int, what I can do is to convert the signed int to unsigned first in the JSON input offline, then I can do JSON unmarshal with the new unsigned array.我找到了解决方案:由于我想要一个字节数组并且字节不能保存有符号整数,我可以做的是首先在 JSON 离线输入中将有符号整数转换为无符号整数,然后我可以对新的无符号数组进行 JSON 解组。

Link to playground: https://play.golang.org/p/Th2DC9AGeEs游乐场链接: https://play.golang.org/p/Th2DC9AGEEs

Code for reference:参考代码:

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