douya7309 2018-03-30 06:50
浏览 3194

在Golang中将interface {}直接转换为int,其中interface将数字存储为字符串

I got a map[string]interface{} because decoding to JSON; with normal data, interface most be only a number but in type string, like this :

var a interface{}

And then all data will be stored into a struct.

type someStruct struct {
   ID string
   Number1 int
   Number2 int
   Number3 int
   Number4 int

So I need to convert interface to int, but can´t do it easily and efficiently because only the code would be, pretty annoying and code does not seem to be readable if you take in mind the fact that I should handle all of possible errors

I would want to convert it directly to int, I´ve been searching for solutions but any of this convertions works as I want

In case you wondering why I don´t just decode it into struct directly, it´s because it´s dynamic data, the actual decoding occurs like this :

type dataIn struct {
   Code int         `json:"code"`
   ID   string      `json:"id"`
   Data interface{} `json:"data"`

And then I handle Data according to code and id, and they all are different data structures, so I can´t directly handle it with JSON

  • 写回答

3条回答 默认 最新

  • doulu2576 2018-03-30 06:56

    Sounds like what you need is a custom unmarshal json method on your main struct. First, unmarshal into your main struct to get your code and id, then use those in a switch statement to determine which struct to use for the rest of the data and unmarshal into that, stirring that struct in your Data field.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?



  • ¥15 DSP28335AD采集实验
  • ¥15 在winods上用C# 怎么编写CAN通信在linux运行
  • ¥15 关于螺旋焊缝的图像处理
  • ¥15 qt 散点图自定义图形
  • ¥100 将USDZ文件转化为带颜色的OBJ文件
  • ¥15 对象代号: , 表单: 不存在!
  • ¥15 WebSocket的问题
  • ¥15 centos上启动kylin后网页报错404
  • ¥20 使用hackrf进行信号收发时接收到的信号幅度太小
  • ¥15 WebSocket的问题