golang json使用10、-10、0表示,true、false、null

package main

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

type A struct {
    Br Boolean `json:"br"`
}

func main() {
    var c A
    json.Unmarshal([]byte(`{"br":"true"}`), &c)
    fmt.Println(c)

}

type Boolean int

const (
    isTrue  = 10
    isFalse = -10
    isNull  = 0
)

func (b Boolean) MarshalJSON() (by []byte, err error) {
    switch b {
    case isTrue:
        by = []byte("true")
    case isFalse:
        by = []byte("false")
    default:
        by = []byte("null")
    }
    return
}

func (b *Boolean) UnmarshalJSON(data []byte) error {
    switch string(data) {
    case `1`, `t`, `T`, `true`, `TRUE`, `True`, `"1"`, `"t"`, `"T"`, `"true"`, `"TRUE"`, `"True"`:
        *b = isTrue
    case `0`, `f`, `F`, `false`, `FALSE`, `False`, `"0"`, `"f"`, `"F"`, `"false"`, `"FALSE"`, `"False"`:
        *b = isFalse
    case `null`:
        *b = isNull
    default:
        return errors.New("不是正确类型")
    }
    return nil
}

func (b Boolean) IsNull() bool {
    return b == isNull
}

func (b Boolean) IsBool() bool {
    return b == isTrue
}

 

posted @ 2022-08-28 22:09  大道至简,小而蕴真  阅读(146)  评论(0编辑  收藏  举报