微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

json编码反思

遇到了调用json.Marshal无法编码的类型,每次编码该结构体,返回错误信息:

json: unsupported type: context.CancelFunc

可能还会遇到各种各样不能编码的情况。

反思1:

json库中介绍说:

Marshal traverses the value v recursively. If an encountered value implements the Marshaler interface and is not a nil pointer,Marshal calls its MarshalJSON method to produce JSON. If no MarshalJSON method is present but the value implements encoding.TextMarshaler instead,Marshal calls its MarshalText method and encodes the result as a JSON string.

尝试实现了FieldsMarshalJSON方法,确实生效了。但这样需要声明的类型去实现这个方法调用方一般没有权限修改

package main

import (
"encoding/json"
"fmt"
"context"
)

type Fields map[string]interface{}

//重写方法类型
func (fields Fields) MarshalJSON() ([]byte,error) {
return []byte("{}"),nil
}

type Right struct {
Data Fields
Cancel context.CancelFunc json:"-"
}

func main() {
right := Right{
Data: Fields{
"id": 1,},}

data,err := json.Marshal(right)
if err != nil {
    fmt.Println(err)
    return
}

fmt.Println(string(data))

}

输出

{"Data":{}}

反思2

使用json中的tag字段,表明不需要编码该字段。在代码中校验之后,确实可行。如上,代码中的Cancel声明为-

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐