tuk tuk - 18 days ago 9
JSON Question

Using EasyJSON with golang

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

Answer

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.

Comments