dtlzdofl66441 2017-01-13 10:53
浏览 67
已采纳

easyjson解组数组进入结构

I started working with golang and easyjson recently. Now I have to unmarshal a json array into a struct to work with it. So here's what I got.

The incoming JSON-data looks like this

[
    {
        "Item1":true,
        "Item2":"hello",
        "Item3":{
            "A": 1,
        },
    },
    ...
]

My struct:

package something

//easyjson:json
type Item struct {
    Item1 bool
    Item2 string
    Item3 SubItem
}

//easyjson:json
type SubItem struct {
    A int      
}

(I build the *_easyjson.go file)

And here's how I would use easyjson:

func ConvertJsonToItem(jsondata string) Item {
    var item Item
    lexer := jlexer.Lexer{Data: []byte(jsondata)}

    item.UnmarshalEasyJSON(&lexer)
    if lexer.Error() != nil {
        panic(lexer.Error())
    }
    return Item
}

That won't work, I know, because the json consists of an array of "Item"-structs. But writing something like

var items []Item

won't work either because I can't execute UnmarshalEasyJSON on a slice. I'm using easyjson because it's the fastet way to handle json data.

So my question is: how can I handle the object array with easyjson.

By the way, I know this question is similar to this one Unmarshal json into struct: cannot unmarshal array into Go value but there the user uses the builtin json package and I have/want to use easyjson. Thank you in advance.

  • 写回答

1条回答 默认 最新

  • dsv768456 2017-01-13 17:09
    关注

    What about

    //easyjson:json
    type ItemSlice []Item
    

    ?

    Then, you can do

    func ConvertJsonToItem(jsondata string) ItemSlice {
        var items ItemSlice
        lexer := jlexer.Lexer{Data: []byte(jsondata)}
    
        items.UnmarshalEasyJSON(&lexer)
        if lexer.Error() != nil {
            panic(lexer.Error())
        }
        return items
    }
    

    And if you really don't want an ItemSlice in your outer code, you can still convert it back to []Item before returning it (but you'll have to do the exact same operation in the other way it you want to marshal it later…).

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

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)