教程集 www.jiaochengji.com
教程集 >  Golang编程  >  golang教程  >  正文 golang 自定义json解析

golang 自定义json解析

发布时间:2022-03-07   编辑:jiaochengji.com
教程集为您提供golang 自定义json解析等资源,欢迎您收藏本站,我们将为您提供最新的golang 自定义json解析资源
<svg xmlns="http://www.w3.org/2000/svg" style="display: none;"><path stroke-linecap="round" d="M5,0 0,2.5 5,5z" id="raphael-marker-block" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0);"/></svg>

在实际开发中,经常会遇到需要定制json编解码的情况。
比如,按照指定的格式输出json字符串,
又比如,根据条件决定是否在最后的json字符串中显示或者不显示某些字段。

如果希望自己定义对象的编码和解码方式,需要实现以下两个接口:

<pre><code>type Marshaler interface { MarshalJSON() ([]byte, error) } type Unmarshaler interface { UnmarshalJSON([]byte) error } </code></pre>

对象实现接口后,编解码时自动调用自定义的方法进行编解码。

下面例子中,自定义编解码方法。
编码时,将map转化为字符串数组。
解码时,将字符串数组转化为map。

<pre><code>package main import ( "encoding/json" "fmt" ) type Bird struct { A map[string]string `json:"a"` } func (bd *Bird) MarshalJSON() ([]byte, error) { l := []string{} for _,v := range bd.A { l = append(l,v) } return json.Marshal(l) } func (bd *Bird) UnmarshalJSON(b []byte) error { l := []string{} err := json.Unmarshal(b, &l) if err != nil { return err } for i,v := range l { k := fmt.Sprintf("%d", i) bd.A[k] = v } return nil } func main() { m := map[string]string{"1": "110", "2":"120", "3":"119"} xiQue := &Bird{A:m} xJson, err := json.Marshal(xiQue) if err != nil { fmt.Println("json.Marshal failed:", err) } fmt.Println("xJson:", string(xJson)) b := `["apple", "orange", "banana"]` baoXiNiao := &Bird{A:map[string]string{}} err = json.Unmarshal([]byte(b), baoXiNiao) if err != nil { fmt.Println("json.Unmarshal failed:", err) } fmt.Println("baoXiNiao:", baoXiNiao) } </code></pre>

output:

<blockquote>

xJson: [“110”,“120”,“119”]
baoXiNiao: &{map[0:apple 1:orange 2:banana]}

</blockquote> <h2>参考</h2>

https://golang.org/pkg/encoding/json/

https://blog.csdn.net/tiaotiaoyly/article/details/38942311

到此这篇关于“golang 自定义json解析”的文章就介绍到这了,更多文章或继续浏览下面的相关文章,希望大家以后多多支持JQ教程网!

您可能感兴趣的文章:
golang 自定义json解析
gorm time.Time 使用钩子函数解决反序列化问题
golang结构体tag的使用
Golang结构体中Tag的使用
golang 读取 mysql null 字符串错误
Golang适用的DTO工具
golang 网络编程(10)文本处理
golang 开源json库使用笔记
Golang解析json数据之延迟解码
PHP JSON转数组

[关闭]
~ ~