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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?