使用工具校验 JSON 格式。
使用工具校验 JSON 格式
使用的 dependency 版本为
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.78</version> </dependency> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.7.0</version> </dependency>
|
源码为
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| public class Main {
public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("{name:\"张三\"}"); list.add("{\"name:\"张三\"}"); list.add("{name\":\"张三\"}"); list.add("{\"name\":\"张三\"}"); for (String s : list) { System.out.println(s); System.out.println("fastJsonValid1(s) = " + fastJsonValid1(s)); System.out.println("fastJsonValid2(s) = " + fastJsonValid2(s)); System.out.println("jacksonValid(s) = " + jacksonValid(s)); System.out.println("gsonValid(s) = " + gsonValid(s)); System.out.println(); }
} public static boolean fastJsonValid1(String test) { JSONValidator from = JSONValidator.from(test); return from.validate(); }
public static boolean fastJsonValid2(String test) { try { JSON.parse(test); } catch (Exception e) { return false; } return true; } public static boolean jacksonValid(String jsonInString) { try { final ObjectMapper mapper = new ObjectMapper(); mapper.readTree(jsonInString); return true; } catch (IOException e) { return false; } } public static boolean gsonValid(String jsonInString) { try { new Gson().fromJson(jsonInString, Object.class); return true; } catch (JsonSyntaxException ex) { return false; } } }
|
运行结果为
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| {name:"张三"} fastJsonValid1(s) = false fastJsonValid2(s) = true jacksonValid(s) = false gsonValid(s) = true
{"name:"张三"} fastJsonValid1(s) = false fastJsonValid2(s) = false jacksonValid(s) = false gsonValid(s) = false
{name":"张三"} fastJsonValid1(s) = false fastJsonValid2(s) = false jacksonValid(s) = false gsonValid(s) = true
{"name":"张三"} fastJsonValid1(s) = true fastJsonValid2(s) = true jacksonValid(s) = true gsonValid(s) = true
|
通过返回值我们可以看到两个问题
- Gson 可以允许 KEY 值不以双引号开头
- FastJson 的 JSONValidator 和 parse 结果不同,parse 允许 key 值不用双引号包裹。
Gson 转换错误格式 JSON
在使用 Gson 的时候发现如下一个情况
这么一个错误格式的 JSON 在 Postman 中能被识别到并且标红。
但是作为参数却能正常发送到后台并且不报错。后台使用的 String 接收,并由 Gson 转义。
转换结果为:
com.google.gson.stream.JsonReader类中PEEKED_UNQUOTED_NAME允许key值不使用双引号。
都被认为是合法的。
如果双引号只出现在前面被认为为非法。