使用EasyJSON与golang

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

Using EasyJSON with golang

问题

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

//easyjson:json
type JSONData struct {
    Data []string
}

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

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

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

英文:

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

答案1

得分: 7

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

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

> mkdir model

> vim models.go

package easyJson

//easyjson:json
type Data struct {
  Name string `json:"name"`
  Age  int    `json:"age"`
}

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

> easyjson -all model/models.go

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

> go run easyjson.go

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

> 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))
 }

很明显,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

package main

import &quot;fmt&quot;
import &quot;time&quot;
import ej &quot;random/golang/easyJson/model&quot;

func main() {
 t1 := time.Now()
 var d ej.Data
 d.Name = &quot;sharathbj&quot;
 d.Age = 23
 data, _ := d.MarshalJSON()
 fmt.Println(string(data))
 fmt.Println(&quot;elapsedTime:&quot;, 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:&quot;name&quot;`
  Age  int    `json:&quot;age&quot;`
}

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

package main

import (
   &quot;fmt&quot;
   &quot;time&quot;
   &quot;encoding/json&quot;
    model &quot;random/golang/easyJson/model&quot;
 )
 func main() {
   t1 := time.Now()
   var d model.Data
   d.Name = &quot;sharathbj&quot;
   d.Age = 23
   data, _ := json.Marshal(d)
   fmt.Println(string(data))
   fmt.Println(&quot;elapsedTime:&quot;, time.Now().Sub(t1))
 }

使用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。

//easyjson:json
type JSONData struct {
    Data []string
}

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

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

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

d := &JSONData{}
d.UnmarshalJSON([]byte(`{"Data" : ["One", "Two", "Three"]}`))
// 或者你也可以使用
// json.Unmarshal(data, d),这也会调用d.UnmarshalJSON
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.

//easyjson:json
type JSONData struct {
    Data []string
}

After define this struct run easyjson &lt;fileName-JSONData-is-defined&gt;.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 := &amp;JSONData{}
d.UnmarshalJSON([]byte(`{&quot;Data&quot; : [&quot;One&quot;, &quot;Two&quot;, &quot;Three&quot;]} `))
// Or you could also use
// json.Unmarshal(data, d) this will also call this d.UnmarshalJSON
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

目录结构如下:

.
├── main.go
└── mypackage
    ├── example.go
    └── example_easyjson.go

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

package mypackage

//easyjson:json
type JSONData struct {
    Data []string
}

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

easyjson -all <file>.go

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

easyjson -all example.go

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

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

package main

import (
    "encoding/json"
    "fmt"

    "github.com/jpudney/stack-overflow/40587860/mypackage"
)

func main() {

    var data mypackage.JSONData
    jsonBlob := `{"Data" : ["One", "Two", "Three"]}`

    err := json.Unmarshal([]byte(jsonBlob), &data)

    if err != nil {
        panic(err)
    }

    fmt.Println(data.Data)

}

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

$ go build -o test
$ ./test
[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

tree  .                                              
.
├── main.go
└── mypackage
    ├── example.go
    └── example_easyjson.go

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

package mypackage

//easyjson:json
type JSONData struct {
    Data []string
}

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:

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:

package main

import (
    &quot;encoding/json&quot;
    &quot;fmt&quot;

    &quot;github.com/jpudney/stack-overflow/40587860/mypackage&quot;
)

func main() {

    var data mypackage.JSONData
    jsonBlob := `{&quot;Data&quot; : [&quot;One&quot;, &quot;Two&quot;, &quot;Three&quot;]}`

    err := json.Unmarshal([]byte(jsonBlob), &amp;data)

    if err != nil {
        panic(err)
    }

    fmt.Println(data.Data)

}

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

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

答案4

得分: 0

序列化:

rawBytes, err := easyjson.Marshal(yourObject)

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

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

反序列化:

err = easyjson.Unmarshal(rawBytes, yourObject)

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

英文:

To serialize:

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():

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

To deserialize:

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:

确定