Using EasyJSON with golang
Solution 1
I don't know why you trying to use easyjson. encoding/json is pretty fine to work with. But though here is the answer for you.
NB: It would be better if you use encoding/json.
//easyjson:json
type JSONData struct {
Data []string
}
After define this struct run easyjson <fileName-JSONData-is-defined>.go
. this will create an extra go file containg
func (v JSONData) MarshalJSON() ([]byte, error)
func (v JSONData) MarshalEasyJSON(w *jwriter.Writer)
func (v *JSONData) UnmarshalJSON(data []byte) errorfunc (v *JSONData)
func UnmarshalEasyJSON(l *jlexer.Lexer)
those methods. Then (un-)marshal using
d := &JSONData{}
d.UnmarshalJSON([]byte(`{"Data" : ["One", "Two", "Three"]} `))
// Or you could also use
// json.Unmarshal(data, d) this will also call this d.UnmarshalJSON
fmt.Println(d)
A full example is here.
Solution 2
Well, easyJson is 4 times faster than normal json(as per its documets) ,in our organization we have used it extensively and yes its faster. Here is a small example to get started. my current directory name is easyJson
vim easyjson.go
package main
import "fmt"
import "time"
import ej "random/golang/easyJson/model"
func main() {
t1 := time.Now()
var d ej.Data
d.Name = "sharathbj"
d.Age = 23
data, _ := d.MarshalJSON()
fmt.Println(string(data))
fmt.Println("elapsedTime:", time.Now().Sub(t1))
}
create a directory named model ,where your structures are defined and new go file models.go
mkdir model
vim models.go
package easyJson
//easyjson:json
type Data struct {
Name string `json:"name"`
Age int `json:"age"`
}
Now run command to create a easyjson file (-all specified to reference all the structure inside a given file)
easyjson -all model/models.go
now a new file will be generated models_easyjson.go using which marshaling/unmarshaling will be referenced
go run easyjson.go
To compare easyjson with normal encoding/json ,below is the code
vim normaljson.go
package main
import (
"fmt"
"time"
"encoding/json"
model "random/golang/easyJson/model"
)
func main() {
t1 := time.Now()
var d model.Data
d.Name = "sharathbj"
d.Age = 23
data, _ := json.Marshal(d)
fmt.Println(string(data))
fmt.Println("elapsedTime:", time.Now().Sub(t1))
}
Clearly easyjson is 7 micro second faster than normal json ,and you will see its impact when you do it for bigger structures , u can see the source code below .
https://github.com/sharathbj/random/tree/master/golang/easyJson
Cheers!!
tuk
Updated on June 04, 2022Comments
-
tuk almost 2 years
Let's say I have a struct like below:-
//easyjson:json type JSONData struct { Data []string }
I want to un-marshal the below json to
JSONData
struct{"Data" : ["One", "Two", "Three"]}
Can someone let me know how can I use easyjson to un-marshal a json in Golang? I could not find any example in their
README