# Работа с JSON файлами

JSON (JavaScript Object Notation) - текстовый формат обмена данными, легко читаемый людьми и основанный на синтаксисе Javascript. JSON, как правило, используется с Javascript, если быть более точным - при обмене данными между Javascript и сервером. Стоит отметить, что JSON обладает существенным преимуществом перед XML - он менее избыточен.

Пример JSON объекта:

```
{
  userId: 32,
  firstName: "Алексей",
  lastName: "Голобурдин",
  address: {
    country: "Россия",
    city: "Москва"
  },
  phone: "8 (905) 777 77 77"
}
```

Итак, рассмотрим использование отличной java библиотеки для генерирования и парсинга JSON - json-simple, официальный сайт на google code. Кстати, там можно найти немало отличных примеров!

Cоздадим JSON строку!

```
//import org.json.simple.JSONObject;

JSONObject resultJson = new JSONObject();

resultJson.put("name","foo");
resultJson.put("num",new Integer(100));
resultJson.put("is_vip",new Boolean(true));
resultJson.put("nickname",null);
System.out.print(obj.toString());
// {"name": "foo", "num": 100, "is_vip": true, "nickname: null}


JSONArray ar = new JSONArray();
JSONObject obj = new JSONObject();
JSONObject resultJson = new JSONObject();

ar.add("first");
ar.add(new Integer(100));

obj.put("one", "two");
obj.put("three", "four");

resultJson.put("paramsArray", ar);
resultJson.put("paramsObj", obj);
resultJson.put("paramsStr", "some string");
System.out.print(obj.toString());
// {"paramsArray": ["first", 100],
//  "paramsObj": {"one": "two", "three": "four"},
//  "paramsStr": "some string"}
```

Парсинг JSON

```
String json = "{paramsArray: [\"first\", 100],"
            + "paramsObj: {one: \"two\", three: \"four\"},"
            + "paramsStr: \"some string\"}";

JSONParser parser = new JSONParser();

Object obj = parser.parse(json);
JSONObject jsonObj = (JSONObject) obj;
System.out.println(jsonObj.get("paramsStr"));
// some string

JsonObject jo = jsonObj.get("paramsObj");
System.out.println(jo.get("three"));
// four

JsonArray ja = jsonObj.get("paramsArray");
System.out.println(ja.get(1));
// 100
```

Вопрос 1.

В каких ситуациях полезно применять JSON для хранения данных? Придумайте пример.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://comaqa.gitbook.io/java-automation/rabota-s-failami/rabota-s-json-failami.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
