猿问

如何在 JSON 中自定义封送映射键

我无法理解 custom marshal intto的奇怪行为string。


这是一个例子:


package main


import (

    "encoding/json"

    "fmt"

)


type Int int


func (a Int) MarshalJSON() ([]byte, error) {

    test := a / 10

    return json.Marshal(fmt.Sprintf("%d-%d", a, test))

}


func main() {


    array := []Int{100, 200}

    arrayJson, _ := json.Marshal(array)

    fmt.Println("array", string(arrayJson))


    maps := map[Int]bool{

        100: true,

        200: true,

    }

    mapsJson, _ := json.Marshal(maps)

    fmt.Println("map wtf?", string(mapsJson))

    fmt.Println("map must be:", `{"100-10":true, "200-20":true}`)

}

输出是:


array ["100-10","200-20"]

map wtf? {"100":true,"200":true}

map must be: {"100-10":true, "200-20":true}

https://play.golang.org/p/iiUyL2Hc5h_P


我错过了什么?


胡说叔叔
浏览 82回答 2
2回答

绝地无双

这是预期的结果,记录在json.Marshal():映射值编码为 JSON 对象。映射的键类型必须是字符串、整数类型或实现 encoding.TextMarshaler。通过应用以下规则对映射键进行排序并将其用作 JSON 对象键,并遵守针对上述字符串值描述的 UTF-8 强制转换:- string keys are used directly- encoding.TextMarshalers are marshaled- integer keys are converted to strings请注意,映射键的处理方式与属性值的处理方式不同,因为 JSON 中的映射键是始终为值的属性名称string(而属性值可能是 JSON 文本、数字和布尔值)。根据文档,如果您希望它也适用于地图键,请实施encoding.TextMarshaler:func (a Int) MarshalText() (text []byte, err error) {&nbsp; &nbsp; test := a / 10&nbsp; &nbsp; return []byte(fmt.Sprintf("%d-%d", a, test)), nil}(请注意,它MarshalText()应该返回“只是”简单文本,而不是 JSON 文本,因此我们在其中省略了 JSON 封送处理!)这样,输出将是(在Go Playground上尝试):array ["100-10","200-20"] <nil>map wtf? {"100-10":true,"200-20":true} <nil>map must be: {"100-10":true, "200-20":true}请注意,这就encoding.TextMarshaler足够了,因为在编组为值时也会检查它,而不仅仅是映射键。所以你不必同时实现encoding.TextMarshaler和json.Marshaler。如果你同时实现了这两者,当值被编组为“简单”值和映射键时,你可以有不同的输出,因为json.Marshaler在生成值时优先:func (a Int) MarshalJSON() ([]byte, error) {&nbsp; &nbsp; test := a / 100&nbsp; &nbsp; return json.Marshal(fmt.Sprintf("%d-%d", a, test))}func (a Int) MarshalText() (text []byte, err error) {&nbsp; &nbsp; test := a / 10&nbsp; &nbsp; return []byte(fmt.Sprintf("%d-%d", a, test)), nil}这次输出将是(在Go Playground上试试):array ["100-1","200-2"] <nil>map wtf? {"100-10":true,"200-20":true} <nil>map must be: {"100-10":true, "200-20":true}

侃侃尔雅

接受的答案很好,但我不得不重新搜索足够多的时间,所以我想通过示例给出关于编组/解组的完整答案,所以下次我可以只复制粘贴作为起点:)我经常搜索的内容包括:将自定义类型编码到 sql 数据库json 将 enum int 编码为字符串json编码映射键但不编码值在这个例子中,我创建了一个自定义的 Weekday 类型,它匹配 time.Weekday int 值,但允许请求/响应 json 和数据库中的字符串值同样的事情可以用任何使用 iota 的 int 枚举来完成,以便在 json 和数据库中具有人类可读的值游乐场测试示例:https://go.dev/play/p/aUxxIJ6tY9K重要的一点在这里:var (&nbsp; &nbsp; // read/write from/to json values&nbsp; &nbsp; _ json.Marshaler&nbsp; &nbsp;= (*Weekday)(nil)&nbsp; &nbsp; _ json.Unmarshaler = (*Weekday)(nil)&nbsp; &nbsp; // read/write from/to json keys&nbsp; &nbsp; _ encoding.TextMarshaler&nbsp; &nbsp;= (*Weekday)(nil)&nbsp; &nbsp; _ encoding.TextUnmarshaler = (*Weekday)(nil)&nbsp; &nbsp; // read/write from/to sql&nbsp; &nbsp; _ sql.Scanner&nbsp; &nbsp;= (*Weekday)(nil)&nbsp; &nbsp; _ driver.Valuer = (*Weekday)(nil))// MarshalJSON marshals the enum as a quoted json stringfunc (w Weekday) MarshalJSON() ([]byte, error) {&nbsp; &nbsp; return []byte(`"` + w.String() + `"`), nil}func (w Weekday) MarshalText() (text []byte, err error) {&nbsp; &nbsp; return []byte(w.String()), nil}func (w *Weekday) UnmarshalJSON(b []byte) error {&nbsp; &nbsp; return w.UnmarshalText(b)}func (w *Weekday) UnmarshalText(b []byte) error {&nbsp; &nbsp; var dayName string&nbsp; &nbsp; if err := json.Unmarshal(b, &dayName); err != nil {&nbsp; &nbsp; &nbsp; &nbsp; return err&nbsp; &nbsp; }&nbsp; &nbsp; d, err := ParseWeekday(dayName)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; return err&nbsp; &nbsp; }&nbsp; &nbsp; *w = d&nbsp; &nbsp; return nil}// Value is used for sql exec to persist this type as a stringfunc (w Weekday) Value() (driver.Value, error) {&nbsp; &nbsp; return w.String(), nil}// Scan implements sql.Scanner so that Scan will be scanned correctly from storagefunc (w *Weekday) Scan(src interface{}) error {&nbsp; &nbsp; switch t := src.(type) {&nbsp; &nbsp; case int:&nbsp; &nbsp; &nbsp; &nbsp; *w = Weekday(t)&nbsp; &nbsp; case int64:&nbsp; &nbsp; &nbsp; &nbsp; *w = Weekday(int(t))&nbsp; &nbsp; case string:&nbsp; &nbsp; &nbsp; &nbsp; d, err := ParseWeekday(t)&nbsp; &nbsp; &nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return err&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; *w = d&nbsp; &nbsp; case []byte:&nbsp; &nbsp; &nbsp; &nbsp; d, err := ParseWeekday(string(t))&nbsp; &nbsp; &nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return err&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; *w = d&nbsp; &nbsp; default:&nbsp; &nbsp; &nbsp; &nbsp; return errors.New("Weekday.Scan requires a string or byte array")&nbsp; &nbsp; }&nbsp; &nbsp; return nil}请注意,var 块只是强制您正确地实现这些方法,否则它不会编译。另请注意,如果您排除MarshalJSON然后 go 将在它存在时使用MarshalText,因此如果您只希望键具有自定义编组但具有值的默认行为那么您不应该在您的主要类型上使用这些方法,而是具有仅用于映射键的包装器类型type MyType struct{}type MyTypeKey MyTypevar (&nbsp; &nbsp; // read/write from/to json keys&nbsp; &nbsp; _ encoding.TextMarshaler&nbsp; &nbsp;= (*MyTypeKey)(nil)&nbsp; &nbsp; _ encoding.TextUnmarshaler = (*MyTypeKey)(nil))func (w MyTypeKey) MarshalText() (text []byte, err error) {&nbsp; &nbsp; return []byte(w.String()), nil}func (w *MyTypeKey) UnmarshalText(b []byte) error {&nbsp; &nbsp; *w = MyTypeKey(ParseMyType(string(b)))&nbsp; &nbsp; return nil}随意改进这个答案,我希望其他人发现它有帮助,我希望下次我能再次找到它并自己再次搜索它:)
随时随地看视频慕课网APP

相关分类

Go
我要回答