douzhen1234 2013-07-22 19:59
浏览 27
已采纳

如何在Go中将JSON解组到接口

I am trying to simultaneously unmarshal and strip fields from a number of different JSON responses into appropriate Go structs. To do this, I created a Wrappable interface that defines the Unwrap method (which strips the appropriate fields) and pass that interface to the code that unmarshals and unwraps. It looks like the following example (also at http://play.golang.org/p/fUGveHwiz9):

package main

import (
    "encoding/json"
    "fmt"
)

type Data struct {
    A string `json:"a"`
    B string `json:"b"`
}

type DataWrapper struct {
    Elements []Data `json:"elems"`
}

type Wrapper interface {
    Unwrap() []interface{}
}

func (dw DataWrapper) Unwrap() []interface{} {
    result := make([]interface{}, len(dw.Elements))
    for i := range dw.Elements {
        result[i] = dw.Elements[i]
    }
    return result
}

func unmarshalAndUnwrap(data []byte, wrapper Wrapper) []interface{} {
    err := json.Unmarshal(data, &wrapper)
    if err != nil {
        panic(err)
    }
    return wrapper.Unwrap()
}

func main() {
    data := `{"elems": [{"a": "data", "b": "data"}, {"a": "data", "b": "data"}]}`
    res := unmarshalAndUnwrap([]byte(data), DataWrapper{})
    fmt.Println(res)
}

However, when I run the code, Go panics with the following error:

panic: json: cannot unmarshal object into Go value of type main.Wrapper

It seems the unmarshaller doesn't want to be passed a pointer to an interface. I am somewhat surprised by this given that I can get at the underlying type and fields using the reflect package within the unmarshalAndUnwrap method. Can anyone provide insight into this problem and how I might work around it?

  • 写回答

1条回答 默认 最新

  • douguan1887 2013-07-22 20:45
    关注

    As you stated, passing a non-pointer fails. Why are you trying to do this anyway?

    Replace

    res := unmarshalAndUnwrap([]byte(data), DataWrapper{})

    by

    res := unmarshalAndUnwrap([]byte(data), &DataWrapper{})

    It should do the trick and it avoid unnecessary copy.

    This error should help you understand: http://play.golang.org/p/jXxCxPQDOw

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示