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

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

问题描述

如果在Golang中解组时未在json中找到字段,是否可能生成错误?我无法在文档中找到它。是否有任何标签指定该字段为必填项?

Is it possible to generate an error if a field was not found in json while unmarshaling in Golang? I could not find it in documentation. Is there any tag that specifies the field as required?

推荐答案

包将字段设置为required。您将不得不编写自己的 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.

要检查缺少的字段,您将不得不使用指针来区分missing / null和零值:

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
}

完整的工作示例:

Full working example:

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\n", *s.String, *s.Number)
}

播放

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

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