Data can be obtained in different ways and, of course, depends on the tasks. I will try to consider some options for parsing Json .
Note: for each of the examples for parsing, Json will be taken from the question, so that nothing is copied into the answer.
Simple json
Where to get: here / repository on github / or via Maven , etc.
This is the most primitive way. In fact, all that is there is JSONObject and JSONArray .
JSONArray can include several JSONObject , you can loop around it at each iteration to get a JSONObject .JSONObject is an object from which its individual properties can be retrieved.
I would use it for small Json lines, where you don’t need to bother much, or if you’re too lazy to write your handler class based on the code shown below:
// Считываем json Object obj = new JSONParser().parse(jsonString); // Object obj = new JSONParser().parse(new FileReader("JSONExample.json")); // Кастим obj в JSONObject JSONObject jo = (JSONObject) obj; // Достаём firstName and lastName String firstName = (String) jo.get("firstName"); String lastName = (String) jo.get("lastName"); System.out.println("fio: " + firstName + " " + lastName); // Достаем массив номеров JSONArray phoneNumbersArr = (JSONArray) jo.get("phoneNumbers"); Iterator phonesItr = phoneNumbersArr.iterator(); System.out.println("phoneNumbers:"); // Выводим в цикле данные массива while (phonesItr.hasNext()) { JSONObject test = (JSONObject) phonesItr.next(); System.out.println("- type: " + test.get("type") + ", phone: " + test.get("number")); }
The rest of the work with nested arrays is similar. You can add to List, Map, etc.
GSON
Where to get: here / repository on github / or via Maven , etc.
Documentation: http://www.studytrails.com/java/json/java-google-json-introduction/
Allows parsing Json as well as Json-simple , i.e. using JSONObject and JSONArray (see the documentation ), but has a more powerful parsing tool. It is enough to create classes that repeat the structure of Json 'a. To parse the Json from the question, create classes:
class Person { public String firstName; public String lastName; public int age; public Address address; public List<Phones> phoneNumbers; public List<Person> friends; } class Address { public String streetAddress; public String city; public String state; public int postalCode; } class Phones { public String type; public String number; }
Now it suffices to write:
Gson g = new Gson(); Person person = g.fromJson(jsonString, Person.class);
Everything! Magic! Miracle! Now in the person is an object with the type Person , in which there is data with exactly those types that were specified in the created classes! Now you can work with any type, as you always used to do: String, Integer, List, Map and everything else.
// Выведет фамилии всех друзей с их телефонами for (Person friend : person.friends) { System.out.print(friend.lastName); for (Phones phone : friend.phoneNumbers) { System.out.println(" - phone type: " + phone.type + ", phone number : " + phone.number); } } // output: // Snow - phone type: home, phone number : 141 111-1234 // Tompson - phone type: home, phone number : 999 111-1234
Example of parsing in the Map :
...... JSON for parsing:
{ "2":{ "sessions":[ { "time":"13:00", "price":"410" }, { "time":"06:40", "price":"340" }, { "time":"16:50", "price":"370" } ], "name":"Кинокис-L", "locate":"Москва, Садовая-Спасская ул., 21, 56", "metro":"Красные ворота" }, "7":{ "sessions":[ { "time":"06:35", "price":"190" }, { "time":"00:05", "price":"410" } ], "name":"Кинокис-V", "locate":"Павелецкая пл., 2, строение 1", "metro":"Павелецкая" }, "8":{ "sessions":[ { "time":"15:10", "price":"330" } ], "name":"Кинокис-J", "locate":"ул. Пречистенка, 40/2", "metro":"Кропоткинская" }, "9":{ "sessions":[ { "time":"13:00", "price":"600" }, { "time":"08:30", "price":"300" }, { "time":"04:00", "price":"510" }, { "time":"13:15", "price":"340" } ], "name":"Кинокис-U", "locate":"Шарикоподшипниковская ул., 24", "metro":"Дубровка" } }
...... Classes (POJO):
class Seanse { public String name; public String locate public String metro; public List<Sessions> sessions; } class Sessions { public String time; public double price; }
...... Analysis itself looks like this:
Gson g = new Gson(); Type type = new TypeToken<Map<String, Seanse>>(){}.getType(); Map<String, Seanse> myMap = g.fromJson(json, type);
Everything.
Additionally, in GSON you can use annotations, for example: exclude the specified fields during parsing, change the variable name (for example, not personFirstName , but fName ) and much more. See the documentation for details.
Jackson
Where to get: here / repository on github / or via Maven , etc.
Documentation and examples: https://github.com/FasterXML/jackson-docs
Like GSON, it also allows you to work using JSONObject and JSONArray if required, and can also parse based on the provided classes (see example below).
Similarly, it can be used to specify additional requirements due to annotations, for example: not parsit the specified fields, use the custom class constructor, change the variable name (for example, not firstName , but fName ) and much more. See the documentation for details.
ObjectMapper mapper = new ObjectMapper(); Person person = mapper.readValue(jsonString, Person.class); System.out.println("My fio: " + person.firstName + " " + person.lastName + " and my friends are: "); for (Person friend : person.friends) { System.out.print(friend.lastName); for (Phones phone : friend.phoneNumbers) { System.out.println(" - phone type: " + phone.type + ", phone number : " + phone.number); } } // output: // My fio: Json Smith and my friends are: // Snow - phone type: home, phone number : 141 111-1234 // Tompson - phone type: home, phone number : 999 111-1234
Jsonpath
Where to get: via Maven and other collectors / repository on github
Refers to the so-called XPath libraries. Its essence is similar to xpath in xml , that is, it is easy to get some of the information from json 'a, along the specified path. And also allows you to filter by condition.
// Выведет все фамилии друзей List<String> friendsLastnames = JsonPath.read(jsonString, "$.friends[*].lastName"); for (String lastname : friendsLastnames) { System.out.println(lastname); } // output: // Snow // Tompson
An example with a sample by the condition:
// Поиск друга, которому больше 22 лет List<String> friendsWithAges = JsonPath .using(Configuration.defaultConfiguration()) .parse(jsonString) .read("$.friends[?(@.age > 22)].lastName", List.class); for (String lastname : friendsWithAges) { System.out.println(lastname); } // output: // Tompson