普通网友 2017-12-27 06:15
浏览 2
已采纳

在Golang的一个键中解组多种数据类型

I have JSON key which will have any one the below data.

1.{"value": "ve"}

2.{"value": ["ve","ff"]}

3.{"value": [1,2]}

4.{"value": 3}

How to unmarshal into a golang's struct?

  • 写回答

1条回答 默认 最新

  • dongxiong1941 2017-12-27 06:39
    关注

    The easiest way is to just use interface{} in your struct. See:

    package main
    
    import (
        "encoding/json"
        "fmt"
    )
    
    type decoded struct {
        Value interface{}       `json:"value"`
    }
    
    func decode(jstr string) {
        var val decoded
        json.Unmarshal([]byte(jstr), &val)
        fmt.Printf("%v
    ", val.Value)
    }
    
    func main() {
        decode(`{"value": "ve"}`)
        decode(`{"value": ["ve","ff"]}`)
        decode(`{"value": [1,2]}`)
        decode(`{"value": 3}`)
    }
    

    You'll probably need to combine this with stuff in the reflect package or (as I did above) fmt.Sprintf() or similar to actually get at your data. This is, however, good enough to decode and put in a structure:

    $ ./spike 
    ve
    [ve ff]
    [1 2]
    3
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog