go MarshalJSON和UnmarshalJSON

99 阅读1分钟

前言

MarshalJSON函数会在该数据格式被json.marshal序列化成json的时候调用。
UnmarshalJSON函数会在json.UnmarshalJSON将json反序列化成该数据格式的时候调用。

需求

格式化成json字符串的时候,将在原有值之后拼接`MarshalJSON格式化`
反序列化的时候,将在原有json字段值的基础上拼接`UnmarshalJSON格式化`

package main

import (
    "encoding/json"
    "fmt"
)

// 自定义结构体
type customAge struct {
    value string
}

type person struct {
    Age *customAge
}

func (this *customAge) MarshalJSON() ([]byte, error) {
    return json.Marshal(this.value + "MarshalJSON格式化")

}

func (this * customAge) UnmarshalJSON(data []byte) (err error) {
    *this = customAge{
        value: string(data) + "UnmarshalJSON格式化"

    }
    return
}

func main() {
    obj:= person{
        Age: &customAge{
            value: "哈哈哈"
        }
    }
    res, _ := json.Marshal(obj)

    fmt.println(string(res)) // {"Age":"哈哈哈MarshalJSON格式化"}
    
    obj2:=person{}
    json.Unmarshal([]byte(`{"name": "jack", "age": 11111 }`, &obj2)
    fmt.Println(obj2.Age.value) // "11111"UnmarshalJSON格式化 
}