【问题标题】:easyjson unmarshal array into go structeasyjson 将数组解组为 go struct
【发布时间】:2017-01-13 10:53:39
【问题描述】:

我最近开始使用 golang 和 easyjson。现在我必须将一个 json 数组解组到一个结构中才能使用它。 所以这就是我得到的。

传入的 JSON 数据如下所示

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

我的结构:

package something

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

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

(我构建 *_easyjson.go 文件)

这就是我将如何使用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
}

这行不通,我知道,因为 json 由一组“Item”结构组成。但是写类似

var items []Item

也不起作用,因为我无法在切片上执行 UnmarshalEasyJSON。 我使用easyjson是因为它是处理json数据最快的方式。

所以我的问题是:如何使用 easyjson 处理对象数组。

顺便说一句,我知道这个问题与Unmarshal json into struct: cannot unmarshal array into Go value 类似,但用户使用内置的 json 包,我有/想要使用 easyjson。 提前谢谢你。

【问题讨论】:

    标签: json go marshalling unmarshalling


    【解决方案1】:

    怎么样

    //easyjson:json
    type ItemSlice []Item
    

    ?

    那么,你就可以了

    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
    }
    

    如果你真的不想在你的外部代码中使用ItemSlice,你仍然可以在返回之前将它转换回[]Item(但你必须以其他方式执行完全相同的操作你想稍后编组它……)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-08
      • 1970-01-01
      • 1970-01-01
      • 2022-01-27
      • 1970-01-01
      • 2020-04-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多