In this tutorial we will learn how to parse JSON data in Spring Boot using the org.springframework.boot.json.JsonParser.

The simplest way to parse JSON Strings in Spring Boot is by means of the org.springframework.boot.json API which is native in Spring Boot. Let's see a concrete example. Consider the following REST Service: https://jsonplaceholder.typicode.com/todos/1

The JSON returned is a single JSON item:

{
  "userId": 1,
  "id": 1,
  "title": "delectus aut autem",
  "completed": false
}

In order to parse it, we can simply use the RestTemplate and request an Object for that URL. The JsonParser, in turn, will convert the JSON Document into a Map (Key,Value):

String url="https://jsonplaceholder.typicode.com/todos/1";
RestTemplate restTemplate = new RestTemplate();
String resp = restTemplate.getForObject(url, String.class);

JsonParser springParser = JsonParserFactory.getJsonParser();
Map<String, Object> map = springParser.parseMap(resp);

String mapArray[] = new String[map.size()];
System.out.println("Items found: " + mapArray.length);

int i = 0;
for (Map.Entry<String, Object> entry : map.entrySet()) {
		System.out.println(entry.getKey() + " = " + entry.getValue());
		i++;
}

And here's the output when running the above piece of code:

Items found: 4
userId = 1
id = 1
title = delectus aut autem
completed = false

Parsing an array of JSON Documents:

A more complex example consists in parsing a set of JSON items. For example: https://jsonplaceholder.typicode.com/todos/

The above REST Service returns an array of items. In order to parse them we will use the parseList method of the JsonParser as follows:

String url="https://jsonplaceholder.typicode.com/todos/";
RestTemplate restTemplate = new RestTemplate();
String resp = restTemplate.getForObject(url, String.class);

JsonParser springParser = JsonParserFactory.getJsonParser();

List<Object> list = springParser.parseList(resp);

for(Object o : list) {
	if(o instanceof Map) {
		Map<String,Object> map = (Map<String,Object>) o;
		System.out.println("Items found: " + map.size());

		int i = 0;
		for (Map.Entry<String, Object> entry : map.entrySet()) {
			System.out.println(entry.getKey() + " = " + entry.getValue());
			i++;
		}

	}
}