【发布时间】:2021-12-20 21:56:13
【问题描述】:
我无法更改的来源:
{
"perfectly_normal": "bar"
"fooBool": "0"
}
桌子上有什么:
type hwo struct {
normality string `json:"perfectly_normal"`
makeMeBool ?????? `json:"fooBool"`
}
json.Unmarshal(body, hwo)
有什么好办法把"0"/"1"转成false/true?
【问题讨论】:
-
创建自己的类型并为其编写 json marshal/unmarshal 函数。即:
type stringyBool bool,因此stringyBool从 0/1 字符串值进行编组/解组,否则为布尔值。 -
查看问题How to unmarshall both 0 and false as bool from JSON了解torek建议的实施。