[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:
Dmytry Kovalenko
2022-05-02 19:11:24 +03:00
committed by GitHub
parent 6a66c335d7
commit 1dccedcd1d
7 changed files with 185 additions and 0 deletions

View File

@@ -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;
}
}