0
votes

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

1 Answers

1
votes

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…).