Last Updated:

How to work with JSON Simple in Java

JSON in Java is a topic that you need to understand in detail. Beginners will have a hard time, since there is a huge number of complex terms in this section, which means that you can not do without additional material. But thanks to this article, you can learn in detail about the API, the very complexity of working with JSON, and so on. It is recommended to read to the end of this article - it will be able to accurately help with parsing in Java and learn the JSON element at least to a basic extent.

JSON SimpleAPI Overview

An additional tool in Java is used to process JSON. To put it simply, it is called API, and the company developing the language called it JSON Simple. This tool consists of many classes, numbering 13 pieces. However, all of them are not required for processing - only 5 of them are needed. Here's what each of these represents:

  • The first and easiest class to understand is JSON Parser, which parses a string with JSON content. Users will have to use such an element when using java.io.Reader or a full line of code. Nothing else is processed and there is no third-party purpose;
  • The next class that represents an object is called a JSON Object. It inherits from HashMap and also stores key-value pairs. But the main thing it does is to present a JSON string, which allows it to create a vision of the object on which the actions are performed. This class has a write JSON String (Mapmap, Writerout) method, which is required to convert the map into a line of code, on which, subsequently, the actions necessary for the user will be carried out;
  • Json Array is an inherited ArrayList element that is designed to implement special interfaces. We can say that 2 others depend on JSON Array – JSON Aware and JSONStreamAware. They, in turn, are required for third-party actions necessary later (if they need to be carried out by the user later);
  • There is also JSON Value in the list of basic ones - a class for parsing JSON strings into objects necessary for carrying out all sorts of operations in Java. Additionally, the Parser JSON class is used, and several useful methods are used to generate JSON. In addition, there are special features ("escape", Strings) for working with special characters - quotation marks "", as well as other things that can be added (Latin f, n, r and so on);
  • JSON Aware is required in order to convert to a special format and implement an interface to do so. As with all other classes, you can't do without it even in standard work with JSON, not to mention the in-depth use of various development tools in Java.

You can also further highlight the JSON Simple classes, but the user will get acquainted with them further himself, since in the process of training from this article you need to know about the most important thing. And what else makes up the basis for learning JSON parsing is parsing a string and creating a new element. This is what the topic is moving to now, so that a person can easily find the use of APIs in Java in the future.

 

JSON Simple API. Example of parsing a JSON string and creating a new JSON object

After understanding the classes, it is recommended that you begin to look at examples of data applications. You can parse JSON, for example, with content that is information about the weather in a particular part of the world. To get started, it's a good idea to create a maven layout that looks like this:

<!— https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple —>
<dependency>
<groupId>com.googlecode.json-simple</groupId>
<artifactId>json-simple</artifactId>
<version>1.1.1</version>
</dependency>

The user also needs to create JSON Utils to parse the finished data into JSON, represented as a string for conversion into a standard JSON object. Here's what the code for the original example will look like:

packageua.com.prologistic.app;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

public class JsonUtils {

/**
* Method for getting data from the specified link
*
* @param url - link in the form of a URL object (Uniform Resource Locator)
* @return page content on the specified link in @param url
*/
public static String parseUrl(URL url) {
if (url == null) {
return "";
}
StringBuilder stringBuilder = new StringBuilder();
// open a connection to the specified URL
// using the try-with-resources construct
try (BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()))) {

String inputLine;
// read the result line by line into a StringBuilder object
while ((inputLine = in.readLine()) != null) {
stringBuilder.append(inputLine);
System.out.println(inputLine);
}
} catch (IOException e) {
e.printStackTrace();
}
return stringBuilder.toString();
}

parsing some
weather data public static void parseCurrentWeatherJson(String resultJson) {
try {
// convert a string from Json to JSONObject for further parsing
JSONObject weatherJsonObject = (JSONObject) JSONValue.parseWithException(resultJson);

get the name of the city for which we look at the weather
System.out.println("City name: " + weatherJsonObject.get(name"));

// get an array of elements for the weather field
/* ... "weather": [
{
"id": 500,
"main": "Rain"
"description": "light rain",
"icon": "10d"
}
], … */
JSONArray weatherArray = (JSONArray) weatherJsonObject.get("weather");
// get the first element from the array
JSONObject weatherData = (JSONObject) weatherArray.get(0);

print the current weather to the System.out.println console
("Current weather: " + weatherData.get(main"));
// and a description to it
System.out.println("More detailed weather description: " + weatherData.get("description"));

} catch (org.json.simple.parser.ParseException e) {
e.printStackTrace();
}
}

form a new JSON object from the weather data
we need public static String buildWeatherJson() {
// for simplicity of the example, just hardcodem the necessary data in
the JSONObject method jsonObject = new JSONObject();
jsonObject.put(name", "London");
jsonObject.put("main", "Sunny");
jsonObject.put("description", "Frost crackling, There is not a single cloud in the sky");

return jsonObject.toJSONString();
}

// create a URL object from the string specified in the parameter
public static URL createUrl(String link) {
try {
return new URL(link);
} catch(MalformedURLException e) {
e.printStackTrace();
returnnull;
}
}
}

This is how the user can do standard JSON parsing using the API base classes. However, it is necessary to understand that this is not all that needs to be done in the example to obtain the final result. You must also create a Main class to work with utilities in JSON(Utils). Here's what it will look like in this case:

packageua.com.prologistic.app;

import java.net.URL;

public class Main {
/**
* For simplicity and convenience, we use an already formed string
* with current London weather query
* <p>
* you can see other request examples here
* {@see <a href="http://openweathermap.org/current">openweathermap</a>}
* you will also need your API key
*/
public static final String WEATHER_URL =
"http://api.openweathermap.org/data/2.5/weather?q=London,uk" +
"&units=metric&appid=241de9349721df959d8800c12ca4f1f3";

public static void main(String[] args) {
// create a URL from a string
URL url = JsonUtils.createUrl(WEATHER_URL);

// load Json as Java string
String resultJson = JsonUtils.parseUrl(url);
System.out.println("Received JSON:\n" + resultJson);

parse the resulting JSON and print it to the screen
JsonUtils.parseCurrentWeatherJson(resultJson);

generate a new JSON object from the weather data
we need String json = JsonUtils.buildWeatherJson();
System.out.println("JSON:\n" we created + json);
}
}

It remains only to check the result in this case. To do this, the console is intended and this is the code it should output, if everything is correct:

The resulting JSON:

{«coord»:{«lon»:-0.13,»lat»:51.51},»weather»:[{«id»:521,»main»:»Rain»,»description»:»shower rain»,»icon»:»09d»}],»base»:»stations»,»main»:{«temp»:20.48,»pressure»:1013,»humidity»:64,»temp_min»:18,»temp_max»:23},»visibility»:10000,»wind»:{«speed»:6.2,»deg»:220},»rain»:{«1h»:0.2},»clouds»:{«all»:75},»dt»:1472401589,»sys»:{«type»:1,»id»:5091,»message»:0.0429,»country»:»GB»,»sunrise»:1472360901, »sunset»:1472410403},»id»:2643743,»name»:»London»,»cod»:200}

Name of the city: London

Current weather: Rain

More detailed weather description: shower rain

The JSON we created:

{"name":"London","description":"Frost crackling, Not a single cloud in the sky","main""Sunny"}

However, there are also difficulties in the analysis. They are expressed as follows:

  • The request for weather does not pass. This is because the server is not responding or something like that. In this case, it is recommended to replace the API key with another one to try using another resource to output data. The main thing is that the work does not stop at the service, which the user decides to take for his example;
  • If the problem occurs with the maven layout, then you should do a simple Java project, and then add the jar library. After that, JSON Simple should function normally and not cause difficulties and a novice programmer.

This concludes the analysis of the JSON parsing example. This can happen with many types of data. The main thing is to understand what are required for processing and how to use them in parsing with JSON.

JSON-parsers

What else you need to know about parsing in java is a set of JSON tools. They all have their own pros and cons, which is why working with each of them can be very different from each other. And therefore, you will have to select for the situation and for yourself a separate method of parsing. Here's what you can use in the process:

  • DataBind is the most popular method that has the most basic parameters for processing JSON. You only need to specify the class to convert, the Java language itself does all the work for the user, including translating the hierarchy into JSON. However, in short, this option is suitable only when you do not need to process multi-gigabyte JSON, and there are no performance problems;
  • TreeModel—Represents JSON as Java, Node, or JsonElement classes with a special hierarchy structure. The difference from DataBind is that it is more difficult to obtain information – it must be done directly by the programmer. Of the shortcomings, there is also a problem with memory limitation and huge files;
  • StreamingAPI is the most low-level option. It can be used, but it is difficult and suitable for advanced users. The fact is that you need to collect tokens for JSON. But all this is compensated by two significant advantages - memory is minimally consumed, and therefore, very high performance is provided, which is very much appreciated in the process. In general, this method is recommended exclusively for programmers with experience or patient people who want to understand this;
  • Analogues of XPath - this method is additional, but it is not always used. It is needed only when you need to take information from JSON. For example, when you need to get the names of the authors of books in the store, it is possible to prescribe the command "$.store.book[*].author", after which the result will be displayed to the user. However, this method does not work in the opposite direction and does not give all the information from the JSON file. But the upside is that there are data on complex criteria, which is not possible with all methods.

As you can see, there are many ways to get the required data from a JSON file. The main thing is to choose an option for yourself and work with it. And how this is done is already indicated in the article.