<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
<blockquote class="layui-elem-quote" style="width: 100%;overflow:hidden">
作者: lanyang123456
链接: https://blog.csdn.net/lanyang123456/article/details/83115803
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
</blockquote>
到此这篇关于“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转数组