Как парсить json на java
Перейти к содержимому

Как парсить json на java

  • автор:

Parsing JSON with Gson library

Ankit Sinhal

In the previous article we understood the basics of JSON and popular libraries for JSON parsing. In this tutorial we are going to discuss about one of most important library, which most of you have used in your project development. This library is GSON developed by Google. This article will explain you some of the advance features provided by GSON which you can utilize.

For more sake of more details I divided the explanation in two parts. This is the Part 1 of the series.

GSON is open source and standalone library which is used to convert JSON data into java objects and vice versa. You can found it here.

Benefits of Gson?

· Convert any Java object to JSON and vice-versa.

· Support of generic objects.

· Allows to serialize a Collections of objects of the same type.

· Exclude the fields during conversion by using transient keyword or @Expose annotation.

· It handles the null fields, by not including them in serialization output but during de-serialization it is initialized back to null.

· Allow custom representations for objects.

· All the fields by default are included in conversions even private fields.

Using Gson

Gson is a primary class which you can just create by calling new Gson(). There is also a class GsonBuilder available that can be used to create a Gson instance with various settings like version control and so on.

To use with Maven

Add the following dependency in pom.xml with latest version:

To use with Gradle

Add the following dependency in build.gradle with latest version:

If you are not using any build system, then you can download the latest jar file from here and add gson jar in classpath or build path.

Getting Started

Create a new Android project

Here is sample nested JSON which is reading from Android assets folder.

Employee.java

You will notice that fields in the Employee.java have the @SerializedName(“”) annotation. This is used when the property name in the java class does not match the field name in JSON.

In order to do the serialization, we need a Gson object, which handles the conversion and then our JSON to a Java object with fromJson():

Here we converted JSON into our Employee object and displayed values.

The sample code is available at GitHub.

Stay tuned for the Part 2 of this series soon for more advance details on GSON library.

Thanks for reading. To help others please click ❤ to recommend this article if you found it helpful.

# JSON in Java

JSON (JavaScript Object Notation) is a lightweight, text-based, language-independent data exchange format that is easy for humans and machines to read and write. JSON can represent two structured types: objects and arrays. JSON is often used in Ajax applications, configurations, databases, and RESTful web services. The Java API for JSON Processing

(opens new window) provides portable APIs to parse, generate, transform, and query JSON.

# Using Jackson Object Mapper

Example: String to Object

Example: Object to String

# Details

Import statement needed:

# ObjectMapper instance

  • ObjectMapper is threadsafe
  • recommended: have a shared, static instance

# Deserialization:

  • valueType needs to be specified — the return will be of this type
  • Throws
  • IOException — in case of a low-level I/O problem
  • JsonParseException — if underlying input contains invalid content
  • JsonMappingException — if the input JSON structure does not match object structure

Usage example (jsonString is the input string):

# Method for serialization:

String writeValueAsString(Object value)

    — `JsonProcessingException` in case of an error — Note: prior to version 2.1, throws clause included IOException; 2.1 removed it.

# JSON To Object (Gson Library)

Lets assume you have a class called Person with just name

Code:

# JSONObject.NULL

If you need to add a property with a null value, you should use the predefined static final JSONObject.NULL and not the standard Java null reference.

JSONObject.NULL is a sentinel value used to explicitly define a property with an empty value.

Note

Which is a clear violation of Java.equals()

For any non-null reference value x, x.equals(null) should return false

# JSON Builder — chaining methods

(opens new window) while working with JSONObject and JSONArray .

JSONObject example

JSONArray

# Object To JSON (Gson Library)

Lets assume you have a class called Person with just name

Code:

(opens new window) jar must be on the classpath.

# JSON Iteration

Iterate over JSONObject properties

Iterate over JSONArray values

# optXXX vs getXXX methods

JSONObject and JSONArray have a few methods that are very useful while dealing with a possibility that a value your are trying to get does not exist or is of another type.

The same rules apply to the getXXX / optXXX methods of JSONArray .

# Encoding data as JSON

If you need to create a JSONObject and put data in it, consider the following example:

# Decoding JSON data

If you need to get data from a JSONObject , consider the following example:

# Extract single element from JSON

# JsonArray to Java List (Gson Library)

Here is a simple JsonArray which you would like to convert to a Java ArrayList :

Now pass the JsonArray ‘list’ to the following method which returns a corresponding Java ArrayList :

You should add the following maven dependency to your POM.xml file:

Or you should have the jar com.google.code.gson:gson:jar:<version> in your classpath.

# Deserialize JSON collection to collection of Objects using Jackson

Suppose you have a pojo class Person

And you want to parse it into a JSON array or a map of Person objects. Due to type erasure you cannot construct classes of List<Person> and Map<String, Person> at runtime directly (and thus use them to deserialize JSON). To overcome this limitation jackson provides two approaches — TypeFactory and TypeReference .

TypeFactory

The approach taken here is to use a factory (and its static utility function) to build your type for you. The parameters it takes are the collection you want to use (list, set, etc.) and the class you want to store in that collection.

TypeReference

The type reference approach seems simpler because it saves you a bit of typing and looks cleaner. TypeReference accepts a type parameter, where you pass the desired type List<Person> . You simply instantiate this TypeReference object and use it as your type container.

Now let’s look at how to actually deserialize your JSON into a Java object. If your JSON is formatted as an array, you can deserialize it as a List. If there is a more complex nested structure, you will want to deserialize to a Map. We will look at examples of both.

Как парсить json на java

JSON (JavaScript Object Notation) is a lightweight, text-based, language-independent data exchange format that is easy for humans and machines to read and write. JSON can represent two structured types: objects and arrays. An object is an unordered collection of zero or more name/value pairs. An array is an ordered sequence of zero or more values. The values can be strings, numbers, booleans, null, and these two structured types.

Below is a simple example from Wikipedia that shows JSON representation of an object that describes a person. The object has string values for first name and last name, a number value for age, an object value representing the person’s address, and an array value of phone number objects.

JSON Processing in Java : The Java API for JSON Processing JSON.simple is a simple Java library that allow parse, generate, transform, and query JSON.

Getting Started : You need to download the json-simple-1.1 jar and put it in your CLASSPATH before compiling and running the below example codes.

  • For importing jar in IDE like eclipse, refer here.
  • If you are using maven you may use the following maven link https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple/1.1.1

Json-Simple API : It provides object models for JSON object and array structures. These JSON structures are represented as object models using types JSONObject and JSONArray. JSONObject provides a Map view to access the unordered collection of zero or more name/value pairs from the model. Similarly, JSONArray provides a List view to access the ordered sequence of zero or more values from the model.

Java json parser – пример работы парсера

В этом посте мы разберем подробный пример парсера Java JSON. JSON(JavaScript Object Notation) – это простой текстовый формат, который облегчает чтение и запись. Это широко используемый формат обмена данными, поскольку его анализ и генерация просты в использовании.

В языке Java есть несколько способов обработки JSON. В этом примере мы собираемся использовать общий набор инструментов – JSON.simple – и узнаем, как анализировать каждый тип файла.

jsonobject

Установка среды

Перед началом написания кода программы, мы должны установить подходящую среду для компилятора, чтобы распознавать классы JSON. Если необходимо построить проект с помощью Maven, нужно добавить следующую запись в pom.xml:

Иначе необходимо добавить версию json-simple-1.1.1.jar в CLASSPATH.

Пример парсинга JSON

Разберем, как мы можем проанализировать и произвести чтение файла json, для этого нужно создать наш собственный файл, он будет называться jsonTestFile.json. Он имеет следующую структуру:

Теперь необходимо создать файл Java в проекте с именем JsonParseTest и вставить следующий код.

Объясним данный код. После создания экземпляра JSONParser мы создаем объект JSONObject.

Он содержит коллекцию пар ключ-значение, из которых мы можем получить каждое значение. Чтобы распарсить объекты, вызывается метод get() экземпляра JSONObject, определяющий указанный ключ в качестве аргумента.

Важно применить подходящий метод. Для типов массивов в файле json используется JSONArray, который представляет упорядоченную последовательность значений. В программном коде итератор должен использоваться для получения каждого значения массива json.

Структура в файле предполагает создание нового объекта JSONObject для получения значений.

Полученный результат парсинга приведен ниже.

Метод с использованием JsonPATH

Два приведенных выше примера требуют полной десериализации JSON в объект Java перед получением значения. Другой альтернативой является использование JsonPATH, который похож на XPath для JSON и позволяет обходить объекты JSON.

Вам нужно добавить JsonPATH, которую можно получить из репозитория maven.(https://mvnrepository.com/artifact/com.jayway.jsonpath/json-path)

java json parser пример

Средняя оценка 3.2 / 5. Количество голосов: 20

Спасибо, помогите другим — напишите комментарий, добавьте информации к статье.

Или поделись статьей

Видим, что вы не нашли ответ на свой вопрос.

Помогите улучшить статью.

Напишите комментарий, что можно добавить к статье, какой информации не хватает.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *