Java gson parse json file

JSON parsing using Gson for Java

This is simple code to do it, I avoided all checks but this is the main idea.

 public String parse(String jsonLine)

To make the use more generic — you will find that Gson’s javadocs are pretty clear and helpful.

String result = jobject.get(«translatedText»).toString(); This results will include the double quotes. String result = jobject.get(«translatedText»).getAsString(); doesn’t include the quotes.

Al I the only one who thinks Gson overcomplicates things 98% of the time? A simple JSONObject would do, but we all hate try/catch that much?

I need to use the parser class, however, I am getting the MalformedJsonException, so I have to be able to do SetLeinient with JsonParser. How?

In my first gson application I avoided using additional classes to catch values mainly because I use json for config matters

despite the lack of information (even gson page), that’s what I found and used:

Map jsonJavaRootObject = new Gson().fromJson("", Map.class) 

Each time gson sees a <>, it creates a Map (actually a gson StringMap )

Each time gson sees a », it creates a String

Each time gson sees a number, it creates a Double

Each time gson sees a [], it creates an ArrayList

You can use this facts (combined) to your advantage

Finally this is the code that makes the thing

 Map javaRootMapObject = new Gson().fromJson(jsonLine, Map.class); System.out.println( ( (Map) ( (List) ( (Map) ( javaRootMapObject.get("data") ) ).get("translations") ).get(0) ).get("translatedText") ); 

Simplest thing usually is to create matching Object hierarchy, like so:

public class Wrapper < public Data data; static class Data < public Translation[] translations; >static class Translation < public String translatedText; >> 

and then bind using GSON, traverse object hierarchy via fields. Adding getters and setters is pointless for basic data containers.

Wrapper value = GSON.fromJSON(jsonString, Wrapper.class); String text = value.data.translations[0].translatedText; 

I think that’s a typo sort of: Data and Translation only need to be static if they are inner classes.

You can create corresponding java classes for the json objects. The integer, string values can be mapped as is. Json can be parsed like this-

Gson gson = new GsonBuilder().create(); Response r = gson.fromJson(jsonString, Response.class); 

You can use a separate class to represent the JSON object and use @SerializedName annotations to specify the field name to grab for each data member:

public class Response < @SerializedName("data") private Data data; private static class Data < @SerializedName("translations") public Translation[] translations; >private static class Translation < @SerializedName("translatedText") public String translatedText; >public String getTranslatedText() < return data.translations[0].translatedText; >> 

Then you can do the parsing in your parse() method using a Gson object:

Gson gson = new Gson(); Response response = gson.fromJson(jsonLine, Response.class); System.out.println("Translated text: " + response.getTranslatedText()); 

With this approach, you can reuse the Response class to add any other additional fields to pick up other data members you might want to extract from JSON — in case you want to make changes to get results for, say, multiple translations in one call, or to get an additional string for the detected source language.

One way would be created a JsonObject and iterating through the parameters. For example

JsonObject jobj = new Gson().fromJson(jsonString, JsonObject.class); 

Then you can extract bean values like:

String fieldValue = jobj.get(fieldName).getAsString(); boolean fieldValue = jobj.get(fieldName).getAsBoolean(); int fieldValue = jobj.get(fieldName).getAsInt(); 

Using Gson to Solve
I would create a class for individual parameter in the json String. Alternatively you can create one main class called «Data» and then create inner classes similarly. I created separate classes for clarity.

The classes are as follows.

In the class JsonParsing the method «parse» we call gson.fromJson(jsonLine, Data.class) which will convert the String in java objects using Reflection.

Once we have access to the «Data» object we can access each parameter individually.

Didn’t get a chance to test this code as I am away from my dev machine. But this should help.

public class JsonParsing < public void parse(String jsonLine) < Gson gson = new GsonBuilder().create(); Data data = gson.fromJson(jsonLine, Data.class); Translations translations = data.getTranslation(); TranslatedText[] arrayTranslatedText = translations.getArrayTranslatedText(); //this returns an array, based on json string for(TranslatedText translatedText:arrayTranslatedText ) < System.out.println(translatedText.getArrayTranslatedText()); >> > public class Data < private Translations translations; public Translations getTranslation() < return translations; >public void setTranslation(Translations translations) < this.translations = translations; >> public class Translations < private TranslatedText[] translatedText; public TranslatedText[] getArrayTranslatedText() < return translatedText; >public void setTranslatedText(TranslatedText[] translatedText) < this.translatedText= translatedText; >> public class TranslatedText < private String translatedText; public String getTranslatedText() < return translatedText; >public void setTranslatedText(String translatedText) < this.translatedText = translatedText; >> 

Источник

Parse JSON File with Gson library in Java

Gson library is used to parse to and from JSON. Where it will parse the JSON to string and vice versa. Also, it will parse the JSON to a list of model class or model class object. However, Gson also has the option to parse the JSON file. With that in this article, we will discuss different methods that are used with the Gson library to parse the JSON file in Java.

json file gson java

Install Gson library

Well for this tutorial we have used Gradle to install libraries. So, here is the Gradle dependency to install the Gson library.

Also, there is a maven dependency for the Gson library.

 com.google.code.gson gson 2.8.6 

Moreover, if you want to use the Gson library as a JAR file, you can download it from GitHub here.

After installing the Gson library we need to access it in the java class file.

MyClass.java

Parse JSON file

The main focus of this article is to parse the JSON file with a path using Gson library. Further, we have customer_data JSON file at /Users/dell/Downloads/customers_data.json path.

MyClass.java

Here is the sample JSON of the customers_data.json file.

customers_data.json

Additionally, for the respective customers_data.json file, we need a model class to parse JSON from the file.

Customer.java
package com.shadow.technos.javacodelib; import com.google.gson.annotations.SerializedName; public class Customer < @SerializedName("first_name") private String firstName; @SerializedName("last_name") private String lastName; @SerializedName("company_name") private String companyName; @SerializedName("address") private String address; @SerializedName("city") private String city; @SerializedName("county") private String county; @SerializedName("state") private String state; @SerializedName("zip") private Integer zip; @SerializedName("phone1") private String phone1; @SerializedName("phone2") private String phone2; @SerializedName("email") private String email; @SerializedName("web") private String web; public Customer() < >public Customer(String firstName, String lastName, String companyName, String address, String city, String county, String state, Integer zip, String phone1, String phone2, String email, String web) < this.firstName = firstName; this.lastName = lastName; this.companyName = companyName; this.address = address; this.city = city; this.county = county; this.state = state; this.zip = zip; this.phone1 = phone1; this.phone2 = phone2; this.email = email; this.web = web; >public String getFirstName() < return firstName; >public void setFirstName(String firstName) < this.firstName = firstName; >public String getLastName() < return lastName; >public void setLastName(String lastName) < this.lastName = lastName; >public String getCompanyName() < return companyName; >public void setCompanyName(String companyName) < this.companyName = companyName; >public String getAddress() < return address; >public void setAddress(String address) < this.address = address; >public String getCity() < return city; >public void setCity(String city) < this.city = city; >public String getCounty() < return county; >public void setCounty(String county) < this.county = county; >public String getState() < return state; >public void setState(String state) < this.state = state; >public Integer getZip() < return zip; >public void setZip(Integer zip) < this.zip = zip; >public String getPhone1() < return phone1; >public void setPhone1(String phone1) < this.phone1 = phone1; >public String getPhone2() < return phone2; >public void setPhone2(String phone2) < this.phone2 = phone2; >public String getEmail() < return email; >public void setEmail(String email) < this.email = email; >public String getWeb() < return web; >public void setWeb(String web) < this.web = web; >>

Methods to Parse JSON file

After creating a valid JSON file variable and respective model class to parse JSON file from the file path, we have different methods with the Gson library to parse JSON to Customer class.

1. Convert to String from Json File

Initially, we fetch the JSON data from the file using Buffered Reader, later we append the data from each line to String Builder.

MyClass.java
public class MyClass < private static final String TAG = MyClass.class.getSimpleName(); private static Gson gson; public static void main(String[] args)< gson = new Gson(); // path of the file String filePath = "/Users/dell/Downloads/customers_data.json"; try< // get file content as string String readJSONStr = readJSONFromFile(filePath); Customer[] custArray = gson.fromJson(readJSONStr, Customer[].class); for(Customer cust:custArray)< // get first_name of the file String first_name = cust.getFirstName(); System.out.println("first_name: "+first_name); >> catch (IOException e) < e.printStackTrace(); >> private static String readJSONFromFile(String filePath) throws IOException < // Create Buffer reader for the File that is downloaded BufferedReader reader = new BufferedReader(new FileReader(filePath)); // create StringBuilder object StringBuilder stringBuilder = new StringBuilder(); String line; // Append items from the file to string builder String ls = System.getProperty("line.separator"); while ((line = reader.readLine()) != null) < stringBuilder.append(line); stringBuilder.append(ls); >// delete the last new line separator stringBuilder.deleteCharAt(stringBuilder.length() - 1); reader.close(); return stringBuilder.toString(); > >

2. Parse JSON File to Model Class with Reader

We create a Reader object for the file path and parse it to the list of the model class.

MyClass.java

public class MyClass < private static final String TAG = MyClass.class.getSimpleName(); private static Gson gson; public static void main(String[] args)< gson = new Gson(); // path of the file String filePath = "/Users/dell/Downloads/customers_data.json"; try< // reader Reader reader = new FileReader(filePath); // parse JSON from file path to Customer Class Customer[] custArray = gson.fromJson(reader, Customer[].class); for(Customer cust:custArray)< // get first_name of the file String first_name = cust.getFirstName(); System.out.println("first_name: "+first_name); >> catch (IOException e) < e.printStackTrace(); >> >

3. Parse JSON File to Model Class with JsonReader

MyClass.java
public class MyClass < private static final String TAG = MyClass.class.getSimpleName(); private static Gson gson; public static void main(String[] args)< gson = new Gson(); // path of the file String filePath = "/Users/dell/Downloads/customers_data.json"; try< // reader Reader reader = new FileReader(filePath); JsonReader jsonReader = new JsonReader(reader); // parse JSON from file path to Customer Class Customer[] custArray = gson.fromJson(reader, Customer[].class); for(Customer cust:custArray)< // get first_name of the file String first_name = cust.getFirstName(); System.out.println("first_name: "+first_name); >> catch (IOException e) < e.printStackTrace(); >> >

4. Parse JSON File to Model Class with JsonElement

Finally, in this method we convert the JSON file to JsonArray using JsonElement. Further, we parse the JsonArray to Customer object using an iterator.

MyClass.java
public class MyClass < private static final String TAG = MyClass.class.getSimpleName(); private static Gson gson; public static void main(String[] args)< gson = new Gson(); // path of the file String filePath = "/Users/dell/Downloads/customers_data.json"; try< // reader Reader reader = new FileReader(filePath); JsonArray json=(JsonArray)gson.fromJson(reader, JsonElement.class); for(int iterator=0;iterator> catch (IOException e) < e.printStackTrace(); >> >

Conclusion

Lastly, we have discussed four methods on how to parse the JSON file to the Customer class with Gson library in Java. You choose any method of your convenience to Parse JSON.

Источник

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

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

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

jsonobject

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

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

 com.googlecode.json-simple json-simple 1.1  

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

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

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

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

package com.hrvector.javabasics.jsonparsertest; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.Iterator; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; public class JsonParseTest < private static final String filePath = "C:\\Users\\katerina\\Desktop\\jsonTestFile.json"; public static void main(String[] args) < try < // считывание файла JSON FileReader reader = new FileReader(filePath); JSONParser jsonParser = new JSONParser(); JSONObject jsonObject = (JSONObject) jsonParser.parse(reader); // получение строки из объекта String firstName = (String) jsonObject.get("firstname"); System.out.println("The first name is: " + firstName); // получение номера из объекта long jsonObject.get("id"); System.out.println("The id is: " + id); // получение массива JSONArray lang= (JSONArray) jsonObject.get("languages"); // берем элементы массива for(int i=0; iIterator i = lang.iterator(); // берем каждое значение из массива json отдельно while (i.hasNext()) < JSONObject innerObj = (JSONObject) i.next(); System.out.println("language "+ innerObj.get("lang") + " with level " + innerObj.get("knowledge")); >// обрабатываем структуру в объекте JSONObject structure = (JSONObject) jsonObject.get("job"); System.out.println("Into job structure, name: " + structure.get("name")); > catch (FileNotFoundException ex) < ex.printStackTrace(); >catch (IOException ex) < ex.printStackTrace(); >catch (ParseException ex) < ex.printStackTrace(); >catch (NullPointerException ex) < ex.printStackTrace(); >> >

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

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

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

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

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

Output: The first name is: Katerina The id is: 1 The 0 element of the array: The 1 element of the array: language en with level proficient language fr with level advanced Into job structure, name: Java Code

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

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

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

import com.jayway.jsonpath.JsonPath; public class ParseJSON < static String json = ". "; public static void main(String[] args) < String pageName = JsonPath.read(json, "$.pageInfo.pageName"); System.out.println(pageName); Integer posts = JsonPath.read(json, "$.posts.length()"); for(int i=0; i < posts; i++) < String post_id = JsonPath.read(json, "$.posts[" + i + "].post_id"); System.out.println(post_id); >> >

java json parser пример

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

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

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

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

Источник

Читайте также:  Python dictionary set all values
Оцените статью