【发布时间】:2013-07-29 12:19:04
【问题描述】:
我正在使用Google-gson 将 JSON 文件解析为 POJO。如果 JSON 文件的格式不正确,GSON 会抛出异常,这很好。但我也需要类型验证,所以如果出现以下情况会引发错误:
- JSON 字段的类型与 POJO 属性的类型不匹配。
- JSON 中缺少属性。
- JSON 中有一些属性在 POJO 中找不到。
如果我有这门课:
class MyClass {
private String aString;
private int anInt;
private boolean aBoolean;
private String[] anArrayOfStrings;
}
像下面这样的 JSON 在任何情况下都不会验证:
{
"aString": 1234, // int instead of String
"anInt": "asd", // String instead of int
// missing aBoolean field
"anArrayOfStrings": [1, 2, 3, 4], // int array instead of String array
"unexpectedValue": "asd" // A field not present in the POJO
}
有什么方法可以用 GSON 做到这一点吗?否则,是否有其他 JSON 解析和映射库能够以简单的方式做到这一点?我的意思是,不必使用另一个包含模式验证的 JSON,例如 com.sdicons.jsontools。
关于哪些属性和这些属性的类型在 POJO 本身中的信息,所以看起来 GSON 至少能够验证类型很容易,但事实并非如此,它只是猜测值的不正确和缺失值。我需要抛出一个异常。
【问题讨论】:
标签: java json validation