drzb7969753 2017-11-01 14:31
浏览 212
已采纳

将多个JSON类型解析为相同的结构

I am requesting an API which returns JSON containing an array of objects. The problem is that the objects can take two forms. They can either be a string or an object. An example result could look like this:

[
    {"name": "obj1", "key2": ["a", "b"]},
    "obj2",
    {"name": "obj3"}
]

A string element "objX" is equivalent to {"name": "objX"}.

I want to parse this into a slice of the following type:

type Obj struct {
    Name string
    Key2 []string
}

How do I do this in a reasonable fashion?

  • 写回答

2条回答 默认 最新

  • doushenken2833 2017-11-01 15:03
    关注
    package main
    
    import (
        "encoding/json"
        "fmt"
    )
    
    type Obj struct {
        Name string   `json:"name"`
        Key2 []string `json:"key2"`
    }
    
    func (o *Obj) UnmarshalJSON(b []byte) error {
        var name string
        if err := json.Unmarshal(b, &name); err == nil {
            *o = Obj{}
            o.Name = name
            return nil
        }
    
        type Obj2 Obj
        var o2 Obj2
        if err := json.Unmarshal(b, &o2); err != nil {
            return err
        }
        *o = Obj(o2)
        return nil
    }
    
    const payload = `[
        {"name": "obj1", "key2": ["a", "b"]},
        "obj2",
        {"name": "obj3"}
    ]
    `
    
    func main() {
        var objs []*Obj
        if err := json.Unmarshal([]byte(payload), &objs); err != nil {
            panic(err)
        }
        for _, obj := range objs {
            fmt.Printf("Name:%v, Key2:%v
    ", obj.Name, obj.Key2)
        }
    }
    

    https://play.golang.org/p/rmtSOpkYqp

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

报告相同问题?

悬赏问题

  • ¥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 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机