教程集 www.jiaochengji.com
教程集 >  Golang编程  >  golang教程  >  正文 Golang中JSON的使用

Golang中JSON的使用

发布时间:2022-02-12   编辑:jiaochengji.com
教程集为您提供Golang中JSON的使用等资源,欢迎您收藏本站,我们将为您提供最新的Golang中JSON的使用资源
<h1>GO Json</h1> <blockquote>

author: qcliu
date: 2015/07/21

</blockquote> <h3>Abstrct</h3>

介绍go语言中json的使用

<h3>json</h3>

json是一种传输格式,类似与XML,与XML相比可读性略差,但是传输效率高。

<h3>GO Json</h3>

go语言中提供了json的encoder,可以将数据结构转换为json格式。在使用之前,需要导入包

<pre><code>import "encoding/json" </code></pre> <h4>Encode</h4>

使用

<pre><code>func NewEncoder(w io.Writer) *Encoder </code></pre>

创建一个json的encode。

<pre><code>file, _ := os.Create("json.txt") enc := json.NewEncoder(file) err := enc.Encode(&v) </code></pre>

数据结构v会以json格式写入<code>json.txt</code>文件。

<h4>Decode</h4>

使用

<pre><code>func NewDecoder(r io.Reader) *Decoder </code></pre>

创建一个json的decode。

<pre><code>fp, _ os.Open("json.txt") dec := json.NewDecoder(fp) for { var V v err := dec.Decode(&v) if err != nil { break } //use v } </code></pre>

v是一个数据结构空间,decoder会将文件中的json格式按照v的定义转化,存在v中。

<h4>Example</h4> <pre><code>type Person struct { name string age int } type Student struct { p *Person sno int } </code></pre>

对于Student类型,虽然里面有一个指针,gojson一样可以处理。在encode与decode时,会自动的递归下降的进行格式转换。

<h3>Summary</h3> <ul><li>encoder与decoder像是在writer外面封装了一层。会根据指定的数据结构的格式进行读写。如果文件中的json格式与指定的数据结构的格式不一致会出现error。</li> <li>在decoder的过程中,用一个for{}不停的读文件,直到出现error,代表文件结束。在for{}中,每次都要申请一个新的空间,存放从文件中读取出来的数据。</li> </ul> 到此这篇关于“Golang中JSON的使用”的文章就介绍到这了,更多文章或继续浏览下面的相关文章,希望大家以后多多支持JQ教程网!

您可能感兴趣的文章:
Golang解析json数据之延迟解码
golang结构体tag的使用
Go 学习笔记 09 | Golang 结构体与 JSON 互相转换
go、golang结构体对象转Json失败原因总结
Go Web编程--解析JSON请求和生成JSON响应
Golang的 Json string和Map互相转换
Golang json string和Map互相转换
Golang中JSON的使用
gorm time.Time 使用钩子函数解决反序列化问题
golang 网络编程(10)文本处理

[关闭]
~ ~