遇到了调用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.
尝试实现了Fields 的MarshalJSON 方法,确实生效了。但这样需要声明的类型去实现这个方法,调用方一般没有权限修改。
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 声明为- 。 (编辑:李大同)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|