[BAEL-5553] Check whether a string is valid JSON in Java (#12136)
* [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
This commit is contained in:
@@ -0,0 +1,32 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user