Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using EasyJSON with golang

Tags:

json

go

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

like image 745
tuk Avatar asked Dec 29 '25 21:12

tuk


1 Answers

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.

like image 105
sadlil Avatar answered Jan 01 '26 14:01

sadlil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!