使用EasyJSON与golang

huangapple go评论126阅读模式
英文:

Using EasyJSON with golang

问题

假设我有一个如下所示的结构体:

  1. //easyjson:json
  2. type JSONData struct {
  3. Data []string
  4. }

我想要将下面的 JSON 解析为 JSONData 结构体:

  1. {"Data" : ["One", "Two", "Three"]}

有人可以告诉我如何在 Golang 中使用 easyjson 解析 JSON 吗?我在他们的 README 中找不到任何示例。

英文:

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

  1. //easyjson:json
  2. type JSONData struct {
  3. Data []string
  4. }

I want to un-marshal the below json to JSONData struct

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

答案1

得分: 7

easyJson比普通的json快4倍(根据它的文档),在我们的组织中我们广泛使用它,确实更快。这里有一个小例子可以开始。我的当前目录名是easyJson

> vim easyjson.go

  1. package main
  2. import "fmt"
  3. import "time"
  4. import ej "random/golang/easyJson/model"
  5. func main() {
  6. t1 := time.Now()
  7. var d ej.Data
  8. d.Name = "sharathbj"
  9. d.Age = 23
  10. data, _ := d.MarshalJSON()
  11. fmt.Println(string(data))
  12. fmt.Println("elapsedTime:", time.Now().Sub(t1))
  13. }

创建一个名为model的目录,其中定义了你的结构体,并创建一个新的go文件models.go。

> mkdir model

> vim models.go

  1. package easyJson
  2. //easyjson:json
  3. type Data struct {
  4. Name string `json:"name"`
  5. Age int `json:"age"`
  6. }

现在运行命令创建一个easyjson文件(使用**-all**指定引用给定文件中的所有结构体)

> easyjson -all model/models.go

现在将生成一个名为models_easyjson.go的新文件,用于引用编组/解组。

> go run easyjson.go

要将easyjson与普通的encoding/json进行比较,以下是代码

> vim normaljson.go

  1. package main
  2. import (
  3. "fmt"
  4. "time"
  5. "encoding/json"
  6. model "random/golang/easyJson/model"
  7. )
  8. func main() {
  9. t1 := time.Now()
  10. var d model.Data
  11. d.Name = "sharathbj"
  12. d.Age = 23
  13. data, _ := json.Marshal(d)
  14. fmt.Println(string(data))
  15. fmt.Println("elapsedTime:", time.Now().Sub(t1))
  16. }

很明显,easyjson比普通的json快7微秒,当你对更大的结构体进行操作时,你会看到它的影响,你可以在下面看到源代码。
<a> https://github.com/sharathbj/random/tree/master/golang/easyJson

干杯!

英文:

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

  1. package main
  2. import &quot;fmt&quot;
  3. import &quot;time&quot;
  4. import ej &quot;random/golang/easyJson/model&quot;
  5. func main() {
  6. t1 := time.Now()
  7. var d ej.Data
  8. d.Name = &quot;sharathbj&quot;
  9. d.Age = 23
  10. data, _ := d.MarshalJSON()
  11. fmt.Println(string(data))
  12. fmt.Println(&quot;elapsedTime:&quot;, time.Now().Sub(t1))
  13. }

create a directory named model ,where your structures are defined and new go file models.go

> mkdir model

> vim models.go

  1. package easyJson
  2. //easyjson:json
  3. type Data struct {
  4. Name string `json:&quot;name&quot;`
  5. Age int `json:&quot;age&quot;`
  6. }

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

使用EasyJSON与golang

To compare easyjson with normal encoding/json ,below is the code

> vim normaljson.go

  1. package main
  2. import (
  3. &quot;fmt&quot;
  4. &quot;time&quot;
  5. &quot;encoding/json&quot;
  6. model &quot;random/golang/easyJson/model&quot;
  7. )
  8. func main() {
  9. t1 := time.Now()
  10. var d model.Data
  11. d.Name = &quot;sharathbj&quot;
  12. d.Age = 23
  13. data, _ := json.Marshal(d)
  14. fmt.Println(string(data))
  15. fmt.Println(&quot;elapsedTime:&quot;, time.Now().Sub(t1))
  16. }

使用EasyJSON与golang

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 .
<a> https://github.com/sharathbj/random/tree/master/golang/easyJson

Cheers!!

答案2

得分: 6

我不知道为什么你要使用easyjson。encoding/json已经足够好用了。但是,这里有一个答案给你。

注意:最好使用encoding/json。

  1. //easyjson:json
  2. type JSONData struct {
  3. Data []string
  4. }

在定义了这个结构体之后,运行easyjson <fileName-JSONData-is-defined>.go。这将创建一个额外的Go文件,其中包含以下方法:

  1. func (v JSONData) MarshalJSON() ([]byte, error)
  2. func (v JSONData) MarshalEasyJSON(w *jwriter.Writer)
  3. func (v *JSONData) UnmarshalJSON(data []byte) error
  4. func (v *JSONData) UnmarshalEasyJSON(l *jlexer.Lexer)

然后,可以使用以下方式进行(反)序列化:

  1. d := &JSONData{}
  2. d.UnmarshalJSON([]byte(`{"Data" : ["One", "Two", "Three"]}`))
  3. // 或者你也可以使用
  4. // json.Unmarshal(data, d),这也会调用d.UnmarshalJSON
  5. fmt.Println(d)

一个完整的示例在这里

英文:

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.

  1. //easyjson:json
  2. type JSONData struct {
  3. Data []string
  4. }

After define this struct run easyjson &lt;fileName-JSONData-is-defined&gt;.go. this will create an extra go file containg

  1. func (v JSONData) MarshalJSON() ([]byte, error)
  2. func (v JSONData) MarshalEasyJSON(w *jwriter.Writer)
  3. func (v *JSONData) UnmarshalJSON(data []byte) errorfunc (v *JSONData)
  4. func UnmarshalEasyJSON(l *jlexer.Lexer)

those methods.
Then (un-)marshal using

  1. d := &amp;JSONData{}
  2. d.UnmarshalJSON([]byte(`{&quot;Data&quot; : [&quot;One&quot;, &quot;Two&quot;, &quot;Three&quot;]} `))
  3. // Or you could also use
  4. // json.Unmarshal(data, d) this will also call this d.UnmarshalJSON
  5. fmt.Println(d)

A full example is here.

答案3

得分: 0

我使用了README.md文件中的说明进行安装:

go get github.com/mailru/easyjson/...

然后我在我的GOPATH中为这个示例创建了一个目录:

$GOPATH/github.com/jpudney/stack-overflow/40587860

目录结构如下:

  1. .
  2. ├── main.go
  3. └── mypackage
  4. ├── example.go
  5. └── example_easyjson.go

在mypackage/example.go中,我有以下代码:

  1. package mypackage
  2. //easyjson:json
  3. type JSONData struct {
  4. Data []string
  5. }

然后,在mypackage目录中,我运行了README中的以下命令:

easyjson -all <file>.go

其中,我用example替换了<file>。所以最终运行了以下命令:

  1. easyjson -all example.go

这将生成一个名为example_easyjson.go的文件,其中包含生成的代码。

然后,我创建了一个main.go文件来使用生成的代码。文件内容如下:

  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "github.com/jpudney/stack-overflow/40587860/mypackage"
  6. )
  7. func main() {
  8. var data mypackage.JSONData
  9. jsonBlob := `{"Data" : ["One", "Two", "Three"]}`
  10. err := json.Unmarshal([]byte(jsonBlob), &data)
  11. if err != nil {
  12. panic(err)
  13. }
  14. fmt.Println(data.Data)
  15. }

我构建并运行了这个文件,它按预期输出了数据:

  1. $ go build -o test
  2. $ ./test
  3. [One Two Three]
英文:

I installed using the instructions from the README.md file:

> go get github.com/mailru/easyjson/...

Then I created a directory in my GOPATH for this example:

> $GOPATH/github.com/jpudney/stack-overflow/40587860

  1. tree .
  2. .
  3. ├── main.go
  4. └── mypackage
  5. ├── example.go
  6. └── example_easyjson.go

In mypackage/example.go I have the following code:

  1. package mypackage
  2. //easyjson:json
  3. type JSONData struct {
  4. Data []string
  5. }

Then, within the mypackage directory I ran the following command from the README:

> easyjson -all &lt;file&gt;.go

Where I replace &lt;file&gt; with example. So ended up running the following:

  1. easyjson -all example.go

This results in a file called example_easyjson.go which contains the generated code.

I then created a main.go file to us the generated code. The contents of which is:

  1. package main
  2. import (
  3. &quot;encoding/json&quot;
  4. &quot;fmt&quot;
  5. &quot;github.com/jpudney/stack-overflow/40587860/mypackage&quot;
  6. )
  7. func main() {
  8. var data mypackage.JSONData
  9. jsonBlob := `{&quot;Data&quot; : [&quot;One&quot;, &quot;Two&quot;, &quot;Three&quot;]}`
  10. err := json.Unmarshal([]byte(jsonBlob), &amp;data)
  11. if err != nil {
  12. panic(err)
  13. }
  14. fmt.Println(data.Data)
  15. }

I build and ran this file and it outputted the data as expected:

  1. $ go build -o test
  2. $ ./test
  3. [One Two Three]

答案4

得分: 0

序列化:

  1. rawBytes, err := easyjson.Marshal(yourObject)

但是内部它会创建一个新的字节数组,所以如果你可以将其转储到写入器中,可以使用easyjson.MarshalToWriter()或者easyjson.MarshalToHTTPResponseWriter()

  1. _, _, err = easyjson.MarshalToHTTPResponseWriter(yourObject, w)

反序列化:

  1. err = easyjson.Unmarshal(rawBytes, yourObject)

请参阅他们的文档:https://pkg.go.dev/github.com/mailru/easyjson@v0.7.7#Marshal

英文:

To serialize:

  1. rawBytes, err := easyjson.Marshal(yourObject)

But internally it will create a new byte array so if you can dump to writer then use easyjson.MarshalToWriter() or even easyjson.MarshalToHTTPResponseWriter():

  1. _, _, err = easyjson.MarshalToHTTPResponseWriter(yourObject, w)

To deserialize:

  1. err = easyjson.Unmarshal(rawBytes, yourObject)

See their documentation https://pkg.go.dev/github.com/mailru/easyjson@v0.7.7#Marshal

huangapple
  • 本文由 发表于 2016年11月14日 19:38:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/40587860.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定