I am trying to check if json is valid and I am experiencing a bizzare behaviour.
When I append some characters to a parsable json both jackson and gson are parsing it and they ignore the trailing charaters. I want to check if the json is strictly valid. Please help. I tried a couple of flags in mapper.configure()
but I couldn't find the exact setting.
import com.google.gson.JsonParser;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;
public class JSONUtil {
public static void main(String[] args) {
String jsonStr = "{\"outputValueSchemaFormat\": \"\",\"sortByIndexInRecord\": 0,\"sortOrder\":\"descending\"}opdfahf";
System.out.println(JSONUtil.isValidJson(jsonStr));
}
public static boolean isValidJson(String str) {
try {
final ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, true);
mapper.readTree(str);
System.out.println(str);
new JsonParser().parse(str);
} catch (Exception e) {
return false;
}
return true;
}
}
PS: This question is different from this because i have used the same code but it seems that either the library has some bug or some configuration flag is missing. I tried a couple of configuration flag but none seems to work.
Real world parsers consideres as a feature to accept incorrect JSON provided they can understand it. Among errors that they can easily fix (not all parsers do all, but some can fix some):
TL/DR: a parser is required to accept valid Json, it is simply unspecified what it does with incorrect but understandable data...
IMHO, if you want to strictly validate a Json string, you should build by hand a custom validator controling the syntax given at http://json.org/, or even better the ECMA-404 specification.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With