Pascal4eg / Java

 Java | Фишки и трюки

JSON

JSON – невероятно удобный и полезный формат для хранения и обмена данными. Java полностью поддерживает его.

Сериализовать данные можно так:

JSONObject author = new JSONObject();
author.put("name", "J. K. Rowling");
author.put("numberOfBooks", 22);

JSONArray books = new JSONArray();
books.put("Harry Potter and the Philosopher's Stone");
books.put("Harry Potter and the Chamber of Secrets");
books.put("Harry Potter and the Prisoner of Azkaban");

author.put("books", books);
System.out.print(author);

Получится вот такая JSON-строка:

{"books":["Harry Potter and the Philosopher's Stone","Harry Potter and the Chamber of Secrets","Harry Potter and the Prisoner of Azkaban"],"name":"J. K. Rowling","numberOfBooks":22}

Десериализация на Java выглядит примерно так:

JSONObject author = new JSONObject(serializedString);
System.out.println("name: " + author.get("name"));
System.out.println("numberOfBooks: " + author.get("numberOfBooks"));

JSONArray books = (JSONArray) author.get("books");
Iterator<Object> i = books.iterator();
System.out.println("books:");
while (i.hasNext()) {
    System.out.println(i.next());
}

Нужно добавить зависимость:

<dependency>
 <groupId>org.json</groupId>
 <artifactId>json</artifactId>
 <version>20231013</version>
</dependency>