tuk tuk - 1 year ago 204
JSON Question

Using EasyJSON with golang

Let's say I have a struct like below:-

type JSONData struct {
Data []string

I want to un-marshal the below json to

{"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

Answer Source

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.

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

A full example is here.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download