小编Mar*_*one的帖子

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

我无法理解的自定义元帅的一个奇怪的行为intstring.

这是一个例子:

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}`)
}
Run Code Online (Sandbox Code Playgroud)

输出是:

array ["100-10","200-20"]
map wtf? {"100":true,"200":true}
map must be: {"100-10":true, "200-20":true}
Run Code Online (Sandbox Code Playgroud)

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

我错过了什么?

string json dictionary go slice

2
推荐指数
1
解决办法
1045
查看次数

标签 统计

dictionary ×1

go ×1

json ×1

slice ×1

string ×1