Json parser java maven

JAVA intro: Introduction to Maven and JSON Parsing

JAVA intro: Introduction to Maven and JSON Parsing 2019-08-29 2019-08-30 https://culture.singular.uk/wp-content/uploads/2017/12/singular-white.png Singular https://culture.singular.uk/wp-content/uploads/2019/05/glenn-carstens-peters-203007-unsplash.jpg 200px 200px

In this article we will go through Maven installation, environment setup and building a sample project for JSON parsing. If you are familiar with Maven already you can skip to the JSON processing part.

MAVEN INSTALLATION STEP BY STEP

Maven is a project management tool that enables building big and scalable apps, which make use of multiple libraries and modules. Maven can be installed by downloading the zip file from its official website and simply setting the environment variable to the home directory of the unzipped contents. For Windows, the environment variables can be found by simply searching in the windows bar for “environment variables” and then adding a new system variable named M2_HOME. After that we need to find the Path variable from the list of system variables, click “Edit” and add the following value:

For Linux/Unix systems, the maven path variable can be set by executing the following command:

The installation can be verified by simply opening the command line and typing “mvn -version”. It can be used both in Eclipse and in Intelij’s IDEA. The Eclipse IDE must be an Eclipse IDE for Java EE (enterprise edition).

Читайте также:  Html select change selected javascript

In order for Maven to run, the system needs to have installed the java development kid (JDK) which can be downloaded from the Oracle official site or some other distribution of JDK, like AdoptOpenJDK or other vendors that don’t require subscription or licensing. Java can be set the same way as Maven i.e. editing the environment variables (adding a new one named JAVA_HOME and editing the path variable).

CREATING YOUR FIRST MAVEN PROJECT

First we need to create a new Maven project and this can be done by only clicking on the “New” menu both in Eclipse and in InteliJ. For each Maven project you need to have group id(org.example.testproject) and artifact id(testapp). After that by clicking the “Finish” button the project will be created. The group id is commonly used on a company level, so that everyone in that company can find the artifacts and re-use them if needed.

The pom.xml file has been created along with the project. This is the file that Maven uses in order to resolve all the dependencies for the project. We can create new maven modules and add them as a dependency in the pom file, but also we can simply import the libraries (artifacts) that we will need. Maven downloads the packages needed for the app, before the app itself is started.

The Maven project has a class named App that defines the app’s behaviour on startup. For starters we will use the App class to run the first sample project. As mentioned above, the project will be used for parsing JSON. We can parse json by using Jacskon, Gson or simply Json.

Each of these libraries is free to use and you can add it to you project by simply searching on the maven official site for the library that we need and after finding it, we just copy the dependency to our pom.xml file. In order for the dependencies to be resolved the project needs to be built first. To do so, run the Cmd and navigate it to the directory where the Maven project is located. For windows, this can also be done by navigating first to the Maven project on the file system and then typing “cmd” in the address bar. This will open the cmd and it will point to the projects directory. Next, type the following command:

This will build the project and it will output “Success” on the command line output, if no errors occurred during the build.

JAVA JSON PARSING WITH JACKSON

Jackson is a high performance JSON processor which can easily convert a Java object to a JSON string and vice versa. JSON is short for Java Script Object Notation. Most of the communication between front-end and back-end is designed to work with JSON objects, because it is convenient both for the back-end and front-end.

In order to use the Jackson library we need to add the Jackson dependency in the pom.xml under the tag. If there is no dependencies tag, you need to create it and then simply copy the dependency from the Maven’s official website and rebuild the project with the command mentioned above.

mavens-jackson-dependency

The other option to use the Jackson library for JSON processing is to download the jar file and add it to your Java project as an external library. In order to verify whether the library has been imported properly in the project, we can import the ObjectMapper class and if that is successful, the project setup has been completed.

import com.fasterxml.jackson.databind.ObjectMapper;

CONVERT JAVA OBJECT TO JSON USING JACKSON

Each Java object can be transformed to its JSON representation, which will output a variable of type String. This is accomplished by using the ObjectMapper class, provided by Jackson.

//converts the java object to a json string Example example=new Example(); ObjectMapper mapper = new ObjectMapper(); String jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(example);

The last line in the example above can be replaced with the following line, which will also output a JSON string, but in this case it will be formatted by default i.e. without the pretty printer output.

String jsonString =mapper.writeValueAsString(example);

The example class is a simple Java class:

The class must provide getters and setters in order for the ObjectMapper to work properly.

CONVERT JSON STRING TO JAVA OBJECT USING JACKSON

In order to convert a JSON string to a Java object, we will use the ObjectMapper class again. The class that we want to transform the string to must provide setters and a default constructor (no arguments). If no other constructors are provided in the class the default constructor can be also left out, since the Java compiler will create it. But if you have a constructor with one or more arguments, the default constructor must be provided as well.

ObjectMapper objectMapper = new ObjectMapper(); Example resultExample = objectMapper.readValue(jsonString, Example.class);

The jsonString variable used in the example above must be in a JSON format so that the object mapper can convert it to a Java object i.e. to the Example class. A simple JSON string would look like:

If you want to use this string in the project you will need to add escape characters so that Java can read the string properly:

Источник

JSON.simple – Read and Write JSON

JSON.simple is a lightweight JSON processing library that can be used to read and write JSON files and strings. The encoded/decoded JSON will be in full compliance with JSON specification (RFC4627).

JSON.simple library is pretty old and has not been updated since march, 2012. Google GSON library is a good option for reading and writing JSON.

In this Java JSON tutorial, we will first see a quick example of writing to a JSON file and then we will read JSON from the file.

  • Full compliance with JSON specification (RFC4627).
  • Supports encode, decode/parse and escape JSON.
  • Easy to use by reusing Map and List interfaces.
  • Supports streaming output of JSON text.
  • High performance.
  • No dependency on external libraries.

Update pom.xml with json-simple maven dependency.

 com.googlecode.json-simple json-simple 1.1.1 

To write JSON test into the file, we will be working with mainly two classes:

  1. JSONArray : To write data in json arrays. Use its add() method to add objects of type JSONObject .
  2. JSONObject : To write json objects. Use it’s put() method to populate fields.

After populating the above objects, use FileWriter instance to write the JSON file.

package com.howtodoinjava.demo.jsonsimple; import java.io.FileWriter; import java.io.IOException; import org.json.simple.JSONArray; import org.json.simple.JSONObject; public class WriteJSONExample < @SuppressWarnings("unchecked") public static void main( String[] args ) < //First Employee JSONObject employeeDetails = new JSONObject(); employeeDetails.put("firstName", "Lokesh"); employeeDetails.put("lastName", "Gupta"); employeeDetails.put("website", "howtodoinjava.com"); JSONObject employeeObject = new JSONObject(); employeeObject.put("employee", employeeDetails); //Second Employee JSONObject employeeDetails2 = new JSONObject(); employeeDetails2.put("firstName", "Brian"); employeeDetails2.put("lastName", "Schultz"); employeeDetails2.put("website", "example.com"); JSONObject employeeObject2 = new JSONObject(); employeeObject2.put("employee", employeeDetails2); //Add employees to list JSONArray employeeList = new JSONArray(); employeeList.add(employeeObject); employeeList.add(employeeObject2); //Write JSON file try (FileWriter file = new FileWriter("employees.json")) < //We can write any JSONArray or JSONObject instance to the file file.write(employeeList.toJSONString()); file.flush(); >catch (IOException e) < e.printStackTrace(); >> >

To read JSON from file, we will use the JSON file we created in the previous example.

  1. First of all, we will create JSONParser instance to parse JSON file.
  2. Use FileReader to read JSON file and pass it to parser.
  3. Start reading the JSON objects one by one, based on their type i.e. JSONArray and JSONObject .
package com.howtodoinjava.demo.jsonsimple; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; public class ReadJSONExample < @SuppressWarnings("unchecked") public static void main(String[] args) < //JSON parser object to parse read file JSONParser jsonParser = new JSONParser(); try (FileReader reader = new FileReader("employees.json")) < //Read JSON file Object obj = jsonParser.parse(reader); JSONArray employeeList = (JSONArray) obj; System.out.println(employeeList); //Iterate over employee array employeeList.forEach( emp ->parseEmployeeObject( (JSONObject) emp ) ); > catch (FileNotFoundException e) < e.printStackTrace(); >catch (IOException e) < e.printStackTrace(); >catch (ParseException e) < e.printStackTrace(); >> private static void parseEmployeeObject(JSONObject employee) < //Get employee object within list JSONObject employeeObject = (JSONObject) employee.get("employee"); //Get employee first name String firstName = (String) employeeObject.get("firstName"); System.out.println(firstName); //Get employee last name String lastName = (String) employeeObject.get("lastName"); System.out.println(lastName); //Get employee website name String website = (String) employeeObject.get("website"); System.out.println(website); >>
[ >, > ] Lokesh Gupta howtodoinjava.com Brian Schultz example.com

Источник

Пример работы с Json Simple в Java: парсинг и создание JSON

Пример работы с Json Simple в Java: парсинг и создание JSON

Этой статьей я начну серию публикаций по работе с JSON в Java. Для начала пройдусь по знакомым и простым решениям, а затем перейду к продвинутым библиотекам. Примером «простых решений» сегодня будет работа с Json Simple, а именно парсинг (разбор) существующего JSON объекта и создание нового.

Обзор Json Simple API

Json Simple — представляет собой простой API для обработки JSON. Сам API состоит из около 13 классов, основу которых составляют следующие 5 классов:

  1. Класс JSONParser предназначен для разбора строки с JSON-содержимым. Он принимает объект java.io.Reader или строку.
  2. Класс JSONObject — это Java представление JSON строки. Класс JSONObject наследует HashMap и хранит пары ключ — значение. Также у него есть очень полезный метод writeJSONString(Map map, Writer out), который используется для конвертации мапы в JSON строку.
  3. Класс JSONArray представляет собой коллекцию. Он наследует ArrayList и реализует интерфейсы JSONAware и JSONStreamAware .
  4. JSONValue — класс для парсинга JSON строки в Java объекты. Для этого он использует класс JSONParser. JSONValue содержит множество полезных методов для создания JSON из различных типов, например, метод writeJSONString(Object value, Writer out) создаст JSON-строку из Java объекта. Он также имеет методы для работы со специальными (управляющими) символами используя метод escape(String s). С помощью этого метода можно безопасно работать с кавычками «» и такими символами, как \f, \t, \n, \, /, \r, \b и многими другими.
  5. Интерфейс JSONAware . Класс должен реализовывать этот интерфейс, чтобы конвертироваться в JSON формат.

Json Simple API. Пример разбора JSON строки и создания нового JSON объекта

Ниже описан пример парсинга строки с JSON содержимым, а именно текущей погоды в каком-то городе. Я использовал сервис Openweathermap.org для получения данных о погоде.

Если Вы хотите просто попробовать JSON Simple API в действии и не хотите заморачиваться над получением этих данных с какого-то сервиса, то просто скопируйте полученный JSON по этой ссылке: openweather и используйте его в виде обычной строки в Java.

Создание maven проекта

Для удобства я создал простой maven проект в Intellij IDEA и добавил в зависимости последнюю версию json-simple в файле pom.xml:

Источник

Оцените статью