How to Check Whether a Given String Is Valid Json in Java

Check whether the String is a Valid JSON String or not?

If you need to be sure it really is valid JSON you're going to need to parse it. A fast, simple, lightweight parser that I like is json-simple. Have a look at their examples here.

http://code.google.com/p/json-simple/wiki/DecodingExamples#Example_2_-_Faster_way:_Reuse_instance_of_JSONParser

Adapting your code I get:

JSONParser parser = new JSONParser();
ResultSet rs = preparedStatement.executeQuery();

while (rs.next()) {
for (String column : columnsList.split(",")) {
//check whether rs.getString(column) is a valid JSON String?
try{
parser.parse(rs.getString(column));
System.out.println("Valid JSON String data");
} catch (ParseException e) {
System.out.printlnn("Invalid JSON String data");
}
}
}

How to check if JSON is valid in Java using GSON?

I found solution but using org.json library, according to How to check whether a given string is valid JSON in Java

public static boolean isJson(String Json) {
try {
new JSONObject(Json);
} catch (JSONException ex) {
try {
new JSONArray(Json);
} catch (JSONException ex1) {
return false;
}
}
return true;
}

Now random looking string bncjbhjfjhj is false and {"status": "UP"} is true.

How to check if a string is a valid Json Schema?

Draft 2019-09 defines some new keywords that allow you to declare that the contents of a string is JSON and conforms to a given schema. However, these keywords are informative only. No assertions are enforced. You would have to extract that information from the schema and do the validation separately.

It would look something like this.

{
"type": "string",
"contentMediaType": "application/schema+json",
"contentSchema": { "$ref": "https://json-schema.org/draft/2019-09" }
}

Also keep in mind that draft 2019-09 doesn't have a lot of implementations at this point, so you might have difficultly finding tools that understand the new keywords. We've seen quite a bit of progress on that front recently, so hopefully that won't be the case for too much longer.

https://datatracker.ietf.org/doc/html/draft-handrews-json-schema-validation-02#section-8

Spring validate string value is a JSON

This is not provided by available validation annotations, therefore you have to go for a custom implementation. The task is divided into 2 simple steps:

1. Is a given String is in the JSON format

There are multiple libraries that are able to parse (therefore validate) a String whether follows the JSON syntax standard. Let's use my favourite GSON for example (there are many). It depends on what library do you currently use:

String string = "{\"foo\":\"bar\"}"
JsonParser jsonParser = new JsonParser();
try {
jsonParser.parse(string); // valid JSON
} catch (JsonSyntaxException ex) {
/* exception handling */ // invalid JSON
}

2. Custom validation annotation

Start with providing a dependency enabling validations:

  • groupId: org.hibernate
  • artifactId: hibernate-validator

Create an annotation used for the validation:

@Documented
@Constraint(validatedBy = JsonStringValidator.class)
@Target({ ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface JsonString {
String message() default "The String is not in JSON format";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}

... and the validator handling the validation through the annotation:

public class JsonStringValidator implements ConstraintValidator<JsonString, String> {

@Override
public void initialize(JsonString jsonString) { }

@Override
public boolean isValid(String string, ConstraintValidatorContext context) {
// Use an implementation from step 1. A brief example:
try {
new JsonParser().parse(string);
return true; // valid JSON, return true
} catch (JsonSyntaxException ex) {
/* exception handling if needed */
}
return false; // invalid JSON, return false
}
}

The usage is pretty straightforward:

@JsonString
private String expectedJsonString

This implementation is described in detail at Baeldung's.



Related Topics



Leave a reply



Submit