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

2019-09-21 01:19发布

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

3条回答
可以哭但决不认输i
2楼-- · 2019-09-21 01:43

Use JSONObject's constructor from a String

    try {
        JSONObject o = new JSONObject(yourString);
    } catch (JSONException e) {
        LOGGER.error("No valid json");
    }
查看更多
劳资没心,怎么记你
3楼-- · 2019-09-21 01:43
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.

查看更多
三岁会撩人
4楼-- · 2019-09-21 01:55
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;
        }
查看更多
登录 后发表回答