简体   繁体   中英

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.

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...

Use JSONObject's constructor from a String

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM