在 Go 中解组 json:必填字段? [英] Unmarshaling json in Go: required field?

查看:41
本文介绍了在 Go 中解组 json:必填字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果在使用 Go 解析 JSON 输入时找不到字段,是否可能产生错误?

Is it possible to generate an error if a field was not found while parsing a JSON input using Go?

我在文档中找不到它.

是否有任何标签将字段指定为必填字段?

Is there any tag that specifies the field as required?

推荐答案

encoding/json 包中没有将字段设置为必需"的标记.您要么必须编写自己的 MarshalJSON() 方法,要么对缺失的字段进行事后检查.

There is no tag in the encoding/json package that sets a field to "required". You will either have to write your own MarshalJSON() method, or do a post check for missing fields.

要检查缺失的字段,您必须使用指针来区分缺失/空值和零值:

To check for missing fields, you will have to use pointers in order to distinguish between missing/null and zero values:

type JsonStruct struct {
    String *string
    Number *float64
}

完整的工作示例:

package main

import (
    "fmt"
    "encoding/json"
)

type JsonStruct struct {
    String *string
    Number *float64
}

var rawJson = []byte(`{
    "string":"We do not provide a number"
}`)


func main() {
    var s *JsonStruct
    err := json.Unmarshal(rawJson, &s)
    if err != nil {
        panic(err)
    }

    if s.String == nil {
        panic("String is missing or null!")
    }

    if s.Number == nil {
        panic("Number is missing or null!")
    }

    fmt.Printf("String: %s  Number: %f
", *s.String, *s.Number)
}

游乐场

这篇关于在 Go 中解组 json:必填字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆