dougu9895 2014-03-23 19:54
浏览 53
已采纳

在与Go中的基础类型匹配时将JSON解组到接口变量

I'm writing a wrapper to map with some additional functionality I need. Some of the most important things is the ability to marshal and unmarshal the data while retaining genericity. I managed to write an marshaller using the encoding/gob encoder, but since it would be nice if the marshalled data was human readable, I decided to code another implementation with JSON.

I got gob to encode from and decode to generic interface variables neatly by passing it a implementation object instance with Register(). (This resource helped me with the details! http://www.funcmain.com/gob_encoding_an_interface)

However, JSON doesn't have Register(). Let's say we have a value of type

type ConcreteImplementation struct {
    FieldA string
    FieldB string
}

func (c ConcreteImplementation) Key() string {
    return c.FieldA   // ConcreteImplementation implements genericValue
}

in a variable of type

type genericValue interface {
    Key() string
}

When I marshal that, it outputs JSON like this:

{"FieldA":"foo","FieldB":"bar"}

And when I try to unmarshal that again into a variable of type genericValue, it says:

panic: interface conversion: map[string]interface {} is not genericValue: missing method Key EDIT: Oops, actually it says this!

Error with decoding! json: cannot unmarshal object into Go value of genericValue

Quite obviously, it tries to marshal the data like it says here: http://blog.golang.org/json-and-go (See 'Generic JSON with interface{}')

How can I get it to try to fit the data to an specific implementation, like gob decoder would try if the implementation is Register()ed? Register() was godsend, it allowed to marshal and unmarshal generically like it was nothing. How do I get JSON to do the same thing?

  • 写回答

2条回答 默认 最新

  • dqcqcqwq38860 2014-03-23 22:14
    关注

    Allright, got it to work finally. This question provided the answer. Why does json.Unmarshal return a map instead of the expected struct?

    "You've passed to json a pointer to an abstract interface. You should simply pass a pointer to Ping as an abstract interface" - This applied to my situation too. (For some reason a pointer TO an abstract interface was enough for gob package. It seems that I have to study Go interfaces and reflection some more to understand why...)

    I won't still mark this as solved question, if someone has a better answer.

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

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c