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 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line