Index

Jackson

verify json only
try {
	JsonParser parser = new JsonFactory().createParser(json);
	while (parser.nextToken() != null) {
	}
} catch (Exception e) {
	throw new RuntimeException("Invalid json: " + e.getMessage());
}
string to object
ObjectMapper mapper = new ObjectMapper();
String jsonInString = "{key' : 'value'}";
User user = mapper.readValue(jsonInString, ConvertTo.class);
object to string
ObjectMapper mapper = new ObjectMapper();
ConvertFrom object = new ConvertFrom();
String json = mapper.writeValueAsString(object);
pretty format
ObjectMapper mapper = new ObjectMapper();
Object obj = mapper.readValue(json, Object.class);
return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);

json path

lookup jpath
public String extractJpath(String path) {
		Object document = Configuration.defaultConfiguration().jsonProvider().parse(json);
		return mapper.writeValueAsString(JsonPath.read(document, path));
	}
example json path
JSONArray urls = JsonPath.read(document, "$..url");
optional jpath
public String extractJpathOptional(String path) {
        try {
            return extractJpath(path);
        } catch (PathNotFoundException e) {
            return null;
        }
    }
jpath resulting in array
JSONArray array = JsonPath.read(document, path);
        for(int i=0; i< array.size(); i++) {
            Object element = array.get(i);
        }
delete a node through jpath
public String deleteNode(String path) {
        Object document = JsonPath.parse(this.json).delete(path).json();
        return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(document);
    }
set a value through jpath
public String setValue(String path, String value) {
        Object document = JsonPath.parse(this.json).set(path, value).json();
        try {
	        return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(document);
        } catch (JsonProcessingException e) {
            throw new RuntimeIOException(e);
        }
    }
documentation
https://github.com/json-path/JsonPath

Relevant dependencies

jackson-annotations com.fasterxml.jackson.core 2.9.8
jackson-core com.fasterxml.jackson.core 2.9.8
jackson-databind com.fasterxml.jackson.core 2.9.8
json-path com.jayway.jsonpath 2.4.0
json-smart net.minidev 2.3
jsoup org.jsoup 1.11.3
slf4j-api org.slf4j 1.7.25