easyjson
easyjson copied to clipboard
Unmarshal to array of struct
Hi,
Given a struct Test
, that has marshal and unmarshal interfaces generated, is it possible to unmarshal data to []Test
?
I have tried various alternatives like:
var ArrTestType []Test
type ArrTest struct {
ArrTestType //anonymous embedded field
}
but it doesnt work. In this case, easyjson complains that it expects a struct (for the embedded field).
bump
Also bump. I have the same problem with slice of structures. Soon will be year from creating issue. Seems like this library isn't ready for production usage.
Its impossible to add methods to slice type
Try this
type ArrTestType []Test
Thank you for fast response. First of all I create a custom type for slice of structs:
type ItemList []Item
type Item struct {}
Then I ran easyjson -all path/to/file.go
.
Lets check generated code. I see generated methods only for Item
struct. ItemList
type was ignored.
//easyjson:json
type ItemList []Item
//easyjson:json
type Item struct {
Val int
}
func TestUnpack() {
data := []byte(`[{"Val":1}, {"Val":2}]`)
v := ItemList{}
v.UnmarshalJSON(data)
fmt.Println(v)
}
This works fine
Withouth //easyjson:json
dont works, because it's not a struct ( -all
match structs ). I'll think what can be done here
But how about MarshalJSON
? I can't marshal struct that doesn't implement easyjson.Marshaler
interface.
I've tried to add //easyjson:json
build tag but this was not help.
Ooops. My mistake. I've added easyjson tag to package instead of type declaration. After I've added tag before type declaration encoding code had been generated.
I think that this usage hack would be worth to describe in readme. Thank you for help.
This thread helped a lot in my implementation. Thanks! Btw, I found easyjson serialization works consistently and quickly under heavy load testing, while encoding/json
does not.
Withouth
//easyjson:json
dont works, because it's not a struct (-all
match structs ). I'll think what can be done here
@rvasily Sorry, so what is the correct way to generate the easyjson file? "easyjson -all *.go" dose not work. then which command should we use?
zhangruiskyline, I just ran into the same issue. I removed the -all
and it worked. Note, you need to tag each struct with //easyjson:json
as rvasily indicated.
Thanks @anuaimi , how to tag structure with //easyjson:json? do you have a example?
this is an example
//easyjson:json
type ItemList []Item
// easyjson.go
package main
import "fmt"
// easyjson:json
type ItemList []Item
// easyjson:json
type Item struct {
Val int
}
func TestUnpack() {
data := []byte(`[{"Val":1}, {"Val":2}]`)
v := ItemList{}
v.UnmarshalJSON(data)
fmt.Println(v)
}
func main() {
TestUnpack()
}
then I ran easyjson easyjson.go
, new file easyjson_easyjson.go
was created and yet errors shown
Bootstrap failed: 1:24: expected type, found newline
Trying to run go run .
and get empty array []
as a result. Why?