dongshou1856 2014-10-23 03:07
浏览 44
已采纳

多个结构开关?

Let's say I have an application that receives json data in two different formats.

f1 = `{"pointtype":"type1", "data":{"col1":"val1", "col2":"val2"}}`
f2 = `{"pointtype":"type2", "data":{"col3":"val3", "col3":"val3"}}`

And I have a struct associated to each type:

type F1 struct {
  col1 string
  col2 string
}

type F2 struct {
  col3 string
  col4 string
}

Assuming that I use the encoding/json library to turn the raw json data into the struct: type Point { pointtype string data json.RawMessage }

How can I decode the data into the appropiate struct just by knowing the pointtype?

I was trying something along the lines of :

func getType(pointType string) interface{} {
    switch pointType {
    case "f1":
        var p F1
        return &p
    case "f2":
        var p F2
        return &p
    }
    return nil
}

Which is not working because the returned value is an interface, not the proper struct type. How can I make this kind of switch struct selection work?

here is a non working example

  • 写回答

2条回答 默认 最新

  • duankang8114 2014-10-23 03:36
    关注

    You can type switch on the interface returned from your method:

    switch ps := parsedStruct.(type) {
        case *F1:
            log.Println(ps.Col1)
        case *F2:
            log.Println(ps.Col3)
    }
    

    ..etc. Remember, for the encoding/json package to decode properly (via reflection), your fields need to be exported (uppercase first letter).

    Working sample: http://play.golang.org/p/8Ujc2CjIj8

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

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类