Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Validate JSON with Jackson JSON

Tags:

java

json

jackson

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)?

like image 629
NinjaCat Avatar asked Apr 19 '12 11:04

NinjaCat


People also ask

How do I check if JSON is valid?

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.

Is JSON A Jackson?

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.

How does Jackson read nested JSON?

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.


1 Answers

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; } 
like image 124
Perception Avatar answered Sep 28 '22 02:09

Perception