How to validate a string is JSON or not in Java?

瘦欲@ 提交于 2019-12-12 07:05:08

问题


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.

if there is no predefined method then at least tell a code which checks JSON Format or not, without using try catch block..

Thanks in advance...


回答1:


Use JSONObject's constructor from a String

    try {
        JSONObject o = new JSONObject(yourString);
    } catch (JSONException e) {
        LOGGER.error("No valid json");
    }



回答2:


public boolean isValidJson(String jsonStr) {
    Object json = new JSONTokener(data).nextValue();
    if (json instanceof JSONObject || json instanceof JSONArray) {
      return true;
    } else {
      return false;
    }
}

Just pass any string in this function.




回答3:


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;
        }


来源:https://stackoverflow.com/questions/41850039/how-to-validate-a-string-is-json-or-not-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!