[英]How to validate a string is JSON or not in Java?
I've already said, my question is different...question is already asked here , but i want a predefined method in java which checksgiven string is json format or not.我已经说过,我的问题是不同的...问题已经在这里问了,但我想要一个 java 中的预定义方法,它检查给定的字符串是否为 json 格式。
if there is no predefined method then at least tell a code which checks JSON Format or not, without using try catch block..如果没有预定义的方法,那么至少告诉一个检查 JSON 格式的代码,而不使用 try catch 块。
Thanks in advance...提前致谢...
Use JSONObject's constructor from a String从字符串中使用JSONObject 的构造函数
try {
JSONObject o = new JSONObject(yourString);
} catch (JSONException e) {
LOGGER.error("No valid json");
}
public boolean isValidJson(String jsonStr) {
Object json = new JSONTokener(jsonStr)).nextValue();
if (json instanceof JSONObject || json instanceof JSONArray) {
return true;
} else {
return false;
}
}
Just pass any string in this function.只需在此函数中传递任何字符串。
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
*
* @param inputJosn
* @return
* @throws IOException
* @throws JsonParseException
* @throws JsonProcessingException
*/
private static boolean isJsonValid(String inputJosn) throws JsonParseException, IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.enable(DeserializationFeature.FAIL_ON_READING_DUP_TREE_KEY);
JsonFactory factory = mapper.getFactory();
JsonParser parser = factory.createParser(inputJosn);
JsonNode jsonObj = mapper.readTree(parser);
System.out.println(jsonObj.toString());
return true;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.