* [BAEL-5553] Check whether a string is valid JSON in Java * [BAEL-5553] Move implementation to json-2 package * [BAEL-5553] Move mapper creation outside method
33 lines
801 B
Java
33 lines
801 B
Java
package com.baeldung.jsonvalidation;
|
|
|
|
import java.io.IOException;
|
|
|
|
import com.google.gson.Gson;
|
|
import com.google.gson.JsonElement;
|
|
import com.google.gson.JsonParser;
|
|
import com.google.gson.JsonSyntaxException;
|
|
import com.google.gson.TypeAdapter;
|
|
|
|
public class GsonValidator {
|
|
|
|
final TypeAdapter<JsonElement> strictAdapter = new Gson().getAdapter(JsonElement.class);
|
|
|
|
public boolean isValid(String json) {
|
|
try {
|
|
JsonParser.parseString(json);
|
|
} catch (JsonSyntaxException e) {
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
public boolean isValidStrict(String json) {
|
|
try {
|
|
strictAdapter.fromJson(json);
|
|
} catch (JsonSyntaxException | IOException e) {
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
}
|