在JAVA中验证JSON字符串对象格式的最佳方法是什么 [英] What's the best way to validate the format of a JSON string object in JAVA

查看:967
本文介绍了在JAVA中验证JSON字符串对象格式的最佳方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想验证字符串对象是否是有效的json对象,无论其数据是否正确。换句话说,这个json字符串是否格式良好?



例如,我得到了:



abc :123,
cba:233
}



该过程应返回格式异常。
{
abc:123
cba:233
}



应该给同样。



您可能认为这很容易,但我们怎样才能及时完成并避免重复过程(解组不应该依赖于验证结果)?在我们的例子中,处理字符串可能是资源消耗。



但是,如果这个代价是绝对不可避免的,那么我们在java中验证json字符串的最快方式/工具是什么? / p>

请注意,在我们的案例中使用Jersey-json。不幸的是,它在JSON对象格式上没有一个好的验证器。所以基本上传入一个字符串,在它被解组之前,我需要对它应用一个验证器。

解决方案

这是一个很好的库,用于处理JSON。您可以使用 JSONValidatingReader 类来验证JSON格式是否有效。



谈论工具,如果如果您正在寻找Java之外的一些工具,您可以随时尝试 JSONLint 。更快,更简单,更清晰的错误消息,但它是基于网络的。


I will like to validate if the string object is a valid json object, regardless its data correctness. In other words, is this json string well formatted?

For instance, I am given:

"abc":"123", "cba":"233" }

the process should return a format exception. { "abc":"123" "cba":"233" }

should give the same.

You might think this is easy, but how can we do it in a timely fashion and avoid duplicated process(unmarshall should not depend on the result of validation)? processing string can be resource consuming in our cases.

However, if this cost is absolutely unavoidable, what is the quickest way/tool we validate a json string in java?

Just a note, Jersey-json is used in our case. Unfortunately, it doesn't have a good validator on JSON object format. So basically a string gets passed in and before it gets unmarshalled, i need to apply a validator on it.

解决方案

This is a good library for handling JSON. You can use the JSONValidatingReader class to validate whether the JSON format is valid or not.

Talking about tools, if you're looking for some tools outside of Java, you can always feel free to try JSONLint. Quicker, simpler and clearer error message but it's a web-based.

这篇关于在JAVA中验证JSON字符串对象格式的最佳方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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