json - 如何严格解码固定长度数组?

标签 json go unmarshalling

我有一个 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/

相关文章:

go - 定义顶级 Go 模板

java - 如何在java中从xml实体字符串值创建不同的pojo

java - JaxB 解码自定义 xml

json - 在 REST 中为您的状态表示引用 JSON Schema 的最佳实践是什么?

json - Gradle : How to use task's output file data in another task?

python - Golang的TLE(超过时间限制)错误,但使用类似逻辑的Python则没有。但为什么?

json - 将不断变化的类型流解码为结构

android - 数据库数据变化时ListView新增数据没有直接显示

javascript - 从服务器请求 JSON 并用 Javascript 进行解析

mongodb - 如何使用GoLang mongodb驱动程序在mongodb中搜索文档,其中文档中的值为字符串,并且过滤器具有字符串 slice ?