我有一个 JSON 格式的坐标
虽然 API 应始终将它们作为大小为 2 的数组正确返回,但我们如何才能强制结构正确并在解码时引发错误(除了非常手动的过程)。如果 json 无效,请参见示例。
package main
import (
"fmt"
"encoding/json"
)
// ResultType
type Location struct {
Coordinates [2]int `json:"coords,array[20]"`
}
func main() {
fmt.Println("Hello, playground")
result := Location{}
jsonBodyTooManyCoords := `{"coords": [1, 2, 3]}`
json.Unmarshal([]byte(jsonBodyTooManyCoords), &result)
fmt.Println(result) // Prints {1, 2}
result = Location{}
jsonBodyTooManyCoords = `{"coords": [1]}`
json.Unmarshal([]byte(jsonBodyTooManyCoords), &result)
fmt.Println(result) // Prints {1, 0}
}
最佳答案
[H]ow can we enforce the structure is correct and raise an error when unmarshaling [...]?
你不能。
多余的元素被静默丢弃,缺失值作为零值返回(这两个事实都记录在 encoding/json 的文档中)。
另请注意,没有数组修饰符,因此您的结构标记 json:"cords,array[20]"
看起来很奇怪。
如果您想要/需要处理格式错误的 JSON 数组:解码为一个 slice 并检查其长度。
关于json - 如何严格解码固定长度数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56285959/