I am trying to use Jackson JSON take a string and determine if it is valid JSON. Can anyone suggest a code sample to use (Java)?
The best way to find and correct errors while simultaneously saving time is to use an online tool such as JSONLint. JSONLint will check the validity of your JSON code, detect and point out line numbers of the code containing errors.
Jackson allows you to read JSON into a tree model: Java objects that represent JSON objects, arrays and values. These objects are called things like JsonNode or JsonArray and are provided by Jackson.
A JsonNode is Jackson's tree model for JSON and it can read JSON into a JsonNode instance and write a JsonNode out to JSON. To read JSON into a JsonNode with Jackson by creating ObjectMapper instance and call the readValue() method. We can access a field, array or nested object using the get() method of JsonNode class.
Not sure what your use case for this is, but this should do it:
public boolean isValidJSON(final String json) { boolean valid = false; try { final JsonParser parser = new ObjectMapper().getJsonFactory() .createJsonParser(json); while (parser.nextToken() != null) { } valid = true; } catch (JsonParseException jpe) { jpe.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } return valid; }
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