遇到了调用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":{}}