IT

주어진 문자열이 Java에서 유효한 JSON인지 확인하는 방법

lottoking 2020. 6. 25. 07:45
반응형

주어진 문자열이 Java에서 유효한 JSON인지 확인하는 방법


Java에서 JSON 문자열의 유효성을 어떻게 확인합니까? 아니면 정규 표현식을 사용하여 구문 분석 할 수 있습니까?


거친 생각, 그것을 파싱하고 예외를 잡으십시오.

import org.json.*;

public boolean isJSONValid(String test) {
    try {
        new JSONObject(test);
    } catch (JSONException ex) {
        // edited, to include @Arthur's comment
        // e.g. in case JSONArray is valid as well...
        try {
            new JSONArray(test);
        } catch (JSONException ex1) {
            return false;
        }
    }
    return true;
}

이 코드는 github , maven 및 부분적 으로 Android 에서 사용할 수있는 org.json JSON API 구현을 사용 합니다 .


잭슨 도서관

하나의 옵션은 Jackson library 를 사용하는 것 입니다. 먼저 최신 버전을 가져옵니다 (현재).

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.7.0</version>
</dependency>

그런 다음 다음과 같이 정답구현할 수 있습니다 .

import com.fasterxml.jackson.databind.ObjectMapper;

public final class JSONUtils {
  private JSONUtils(){}

  public static boolean isJSONValid(String jsonInString ) {
    try {
       final ObjectMapper mapper = new ObjectMapper();
       mapper.readTree(jsonInString);
       return true;
    } catch (IOException e) {
       return false;
    }
  }
}

Google GSON 옵션

다른 옵션은 Google Gson 을 사용하는 것 입니다. 종속성을 가져옵니다.

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.5</version>
</dependency>

다시, 제안 된 솔루션을 다음과 같이 구현할 수 있습니다.

import com.google.gson.Gson;

public final class JSONUtils {
  private static final Gson gson = new Gson();

  private JSONUtils(){}

  public static boolean isJSONValid(String jsonInString) {
      try {
          gson.fromJson(jsonInString, Object.class);
          return true;
      } catch(com.google.gson.JsonSyntaxException ex) { 
          return false;
      }
  }
}

간단한 테스트는 다음과 같습니다.

//A valid JSON String to parse.
String validJsonString = "{ \"developers\": [{ \"firstName\":\"Linus\" , \"lastName\":\"Torvalds\" }, " +
        "{ \"firstName\":\"John\" , \"lastName\":\"von Neumann\" } ]}";

// Invalid String with a missing parenthesis at the beginning.
String invalidJsonString = "\"developers\": [ \"firstName\":\"Linus\" , \"lastName\":\"Torvalds\" }, " +
        "{ \"firstName\":\"John\" , \"lastName\":\"von Neumann\" } ]}";

boolean firstStringValid = JSONUtils.isJSONValid(VALID_JSON_STRING); //true
boolean secondStringValid = JSONUtils.isJSONValid(NOT_VALID_JSON_STRING); //false

릴리스에서 수정 될 후행 쉼표로 인해 "사소한"문제가있을 수 있습니다 3.0.0.


함께 구글 GSON 당신은 JsonParser을 사용할 수 있습니다 :

import com.google.gson.JsonParser;

JsonParser parser = new JsonParser();
parser.parse(json_string); // throws JsonSyntaxException

당신은 사용할 수 .mayBeJSON (문자열 str을)를 에서 사용할 수를 JSONUtils의 라이브러리입니다.


검증으로 증명하려는 대상에 따라 다릅니다. 다른 사람들이 제안한 것처럼 json을 구문 분석하는 것이 정규 표현식을 사용하는 것보다 낫습니다 .json의 문법은 정규 표현식으로 표현할 수있는 것보다 더 복잡하기 때문입니다.

json이 Java 코드로만 구문 분석되는 경우 동일한 구문 분석기를 사용하여 유효성을 검증하십시오.

그러나 파싱만으로 다른 환경에서 허용되는지 반드시 알려주지는 않습니다. 예 :

  • 많은 파서는 객체 나 배열에서 후행 쉼표를 무시하지만 후행 쉼표에 도달하면 이전 버전의 IE가 실패 할 수 있습니다.
  • 다른 파서는 후행 쉼표를 사용할 수 있지만 그 뒤에 정의되지 않은 / 널 항목을 추가하십시오.
  • 일부 파서는 인용되지 않은 속성 이름을 허용 할 수 있습니다.
  • 일부 파서는 문자열에서 비 ASCII 문자에 다르게 반응 할 수 있습니다.

검증이 매우 철저해야하는 경우 다음을 수행 할 수 있습니다.


String jsonInput = "{\"mob no\":\"9846716175\"}";//Read input Here
JSONReader reader = new JSONValidatingReader();
Object result = reader.read(jsonInput);
System.out.println("Validation Success !!");

stringtree-json 라이브러리를 다운로드하십시오


파싱에 대한 약간의 :

Json, and in fact all languages, use a grammar which is a set of rules that can be used as substitutions. in order to parse json, you need to basically work out those substitutions in reverse

Json is a context free grammar, meaning you can have infinitely nested objects/arrays and the json would still be valid. regex only handles regular grammars (hence the 'reg' in the name), which is a subset of context free grammars that doesn't allow infinite nesting, so it's impossible to use only regex to parse all valid json. you could use a complicated set of regex's and loops with the assumption that nobody will nest past say, 100 levels deep, but it would still be very difficult.

if you ARE up for writing your own parser
you could make a recursive descent parser after you work out the grammar


Here you can find a tool that can validate a JSON file, or you could just deserialize your JSON file with any JSON library and if the operation is successful then it should be valid (google-json for example that will throw an exception if the input it is parsing is not valid JSON).


Using Playframework 2.6, the Json library found in the java api can also be used to simply parse the string. The string can either be a json element of json array. Since the returned value is not of importance here we just catch the parse error to determine that the string is a correct json string or not.

    import play.libs.Json;

    public static Boolean isValidJson(String value) {
        try{
            Json.parse(value);
            return true;
        } catch(final Exception e){
            return false;
        }
    }

IMHO, the most elegant way is using the Java API for JSON Processing (JSON-P), one of the JavaEE standards that conforms to the JSR 374.

try(StringReader sr = new StringReader(jsonStrn)) {
    Json.createReader(sr).readObject();
} catch(JsonParsingException e) {
    System.out.println("The given string is not a valid json");
    e.printStackTrace();
}

Using Maven, add the dependency on JSON-P:

<dependency>
    <groupId>org.glassfish</groupId>
    <artifactId>javax.json</artifactId>
    <version>1.1.4</version>
</dependency>

Visit the JSON-P official page for more informations.


Check whether a given string is valid JSON in Kotlin. I Converted answer of MByD Java to Kotlin

fun isJSONValid(test: String): Boolean {
    try {
        JSONObject(test);
    } catch (ex: JSONException) {
        try {
            JSONArray(test);
        } catch (ex1: JSONException) {
            return false;
        }
    }
    return true;
}

I have found a very simple solution for it.

Please first install this library net.sf.json-lib for it.

    import net.sf.json.JSONException;

    import net.sf.json.JSONSerializer;

    private static boolean isValidJson(String jsonStr) {
        boolean isValid = false;
        try {
            JSONSerializer.toJSON(jsonStr);
            isValid = true;
        } catch (JSONException je) {
            isValid = false;
        }
        return isValid;
    }

    public static void testJson() {
        String vjson = "{\"employees\": [{ \"firstName\":\"John\" , \"lastName\":\"Doe\" },{ \"firstName\":\"Anna\" , \"lastName\":\"Smith\" },{ \"firstName\":\"Peter\" , \"lastName\":\"Jones\" }]}";
        String ivjson = "{\"employees\": [{ \"firstName\":\"John\" ,, \"lastName\":\"Doe\" },{ \"firstName\":\"Anna\" , \"lastName\":\"Smith\" },{ \"firstName\":\"Peter\" , \"lastName\":\"Jones\" }]}";
        System.out.println(""+isValidJson(vjson)); // true
        System.out.println(""+isValidJson(ivjson)); // false
    }

Done. Enjoy


The answers are partially correct. I also faced the same problem. Parsing the json and checking for exception seems the usual way but the solution fails for the input json something like

{"outputValueSchemaFormat": "","sortByIndexInRecord": 0,"sortOrder":847874874387209"descending"}kajhfsadkjh

As you can see the json is invalid as there are trailing garbage characters. But if you try to parse the above json using jackson or gson then you will get the parsed map of the valid json and garbage trailing characters are ignored. Which is not the required solution when you are using the parser for checking json validity.

For solution to this problem see here.

PS: This question was asked and answered by me.


import static net.minidev.json.JSONValue.isValidJson;

and then call this function passing in your JSON String :)


public static boolean isJSONValid(String test) {
    try {
        isValidJSON(test);
        JsonFactory factory = new JsonFactory();
        JsonParser parser = factory.createParser(test);
        while (!parser.isClosed()) {
            parser.nextToken();
        }
    } catch (Exception e) {
        LOGGER.error("exception: ", e);
        return false;
    }
    return true;
}

private static void isValidJSON(String test) {
    try {
        new JSONObject(test);
    } catch (JSONException ex) {
        try {
            LOGGER.error("exception: ", ex);
            new JSONArray(test);
        } catch (JSONException ex1) {
            LOGGER.error("exception: ", ex1);
            throw new Exception("Invalid JSON.");
        }
    }
}

Above solution covers both the scenarios:

  • duplicate key
  • mismatched quotes or missing parentheses etc.

Here is a working example for strict json parsing with gson library:

public static JsonElement parseStrict(String json) {
    // throws on almost any non-valid json
    return new Gson().getAdapter(JsonElement.class).fromJson(json); 
}

See also my other detailed answer in How to check if JSON is valid in Java using GSON with more info and extended test case with various non-valid examples.


A solution using the javax.json library:

import javax.json.*;

public boolean isTextJson(String text) {
    try {
        Json.createReader(new StringReader(text)).readObject();
    } catch (JsonException ex) {
        try {
            Json.createReader(new StringReader(text)).readArray();
        } catch (JsonException ex2) {
            return false;
        }
    }
    return true;
}

참고URL : https://stackoverflow.com/questions/10174898/how-to-check-whether-a-given-string-is-valid-json-in-java

반응형