使用 Go 时如何检测 JSON 中不需要的字段?

问题描述 投票:0回答:1

当使用 Go 将 json 序列化为结构体时,我需要检测 json 中是否存在结构体中不存在的字段。例如:

type Foo struct {
    Bar string `json:"bar"`
}
{
  "bar": 1,
  "baz": 2
}

默认情况下,Go 将忽略

baz
字段并且不对其执行任何操作。如何检测是否存在额外字段并在这种情况下执行某些操作?

我可能可以将 json 解组为

interface{}
而不是预定义的结构,然后检查它有哪些键,但这确实会使我的应用程序其余部分的逻辑变得复杂,并添加很多不必要的验证代码,所以我我宁愿不这样做。

json go serialization
1个回答
0
投票

您可以使用

json.Decoder
DisallowUnknownFields
方法来做到这一点:

package main

import (
    "bytes"
    "encoding/json"
    "fmt"
)

type Foo struct {
    Bar string `json:"bar"`
}

func main() {
    input := []byte(`{
  "bar": "1",
  "baz": 2
}`)
    foo := Foo{}
    br := bytes.NewReader(input)
    decoder := json.NewDecoder(br)
    decoder.DisallowUnknownFields()
    err := decoder.Decode(&foo)
    fmt.Printf("Result: %v\n", err)
}

Go Playground 参考:https://go.dev/play/p/8TRYLnhNiz0

© www.soinside.com 2019 - 2024. All rights reserved.