2013-07-29 51 views
0

我正在使用Google-gson将JSON文件解析为POJO。如果JSON文件格式不正确,GSON会抛出异常,这很好。但是我也需要类型验证,所以如果出现以下错误:Java JSON数据类型验证

  • 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很容易验证至少这些类型,但它不会,它只是猜测不正确值和缺失值的值。我需要抛出一个异常。

回答

0

这不是有效的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 
} 

它改成这样:

{ 
    "aString": 1234, 
    "anInt": "asd", 
    "anArrayOfStrings": [1, 2, 3, 4], 
    "unexpectedValue": "asd" 
} 
+0

哦,是的感谢您指出的错字 – dablak

+1

Tichodroma,你可能会为什么它不是有效的提至OP。也就是说,JSON中的评论是不允许的。 – James