加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

json编码反思

发布时间:2020-12-16 19:32:03 所属栏目:百科 来源:网络整理
导读:遇到了调用 json.Marshal 无法编码的类型,每次编码该结构体,返回错误信息: json: unsupported type: context.CancelFunc 可能还会遇到各种各样不能编码的情况。 反思 1 : json 库中介绍说: Marshal traverses the value v recursively. If an encountere

遇到了调用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声明为-

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读