How to Read a Json File Into a List Gson

Gson library is used to parse to and from JSON. Where information technology will parse the JSON to cord and vice versa. Also, it volition parse the JSON to a list of model grade or model class object. All the same, Gson likewise has the option to parse the JSON file. With that in this commodity, nosotros will hash out different methods that are used with the Gson library to parse the JSON file in Coffee.

json file gson java

Install Gson library

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

dependencies {   implementation 'com.google.code.gson:gson:2.viii.6' }

Also, in that location is a maven dependency for the Gson library.

<dependency>   <groupId>com.google.lawmaking.gson</groupId>   <artifactId>gson</artifactId>   <version>two.8.6</version> </dependency>

Moreover, if you lot desire to utilise the Gson library as a JAR file, yous can download it from GitHub hither.

After installing the Gson library we demand to access it in the coffee class file.

MyClass.coffee
public class MyClass {      private static Gson gson;      public static void main(String[] args){  	      gson = new Gson();     } }

Parse JSON file

The master focus of this commodity 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
public class MyClass {      private static Gson gson;      public static void principal(String[] args){  	     gson = new Gson();  	    // path of the file 	    String filePath = "/Users/dell/Downloads/customers_data.json";      } }

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

customers_data.json
[   {     "first_name": "James",     "last_name": "Barrel",     "company_name": "Benton, John B Jr",     "address": "6649 North Blue Gum St",     "metropolis": "New Orleans",     "county": "Orleans",     "state": "LA",     "zip": 70116,     "phone1": "504-621-8927",     "phone2": "504-845-1427",     "email": "jbutt@gmail.com",     "web": "http://www.bentonjohnbjr.com"   },   {     "first_name": "Josephine",     "last_name": "Darakjy",     "company_name": "Chanay, Jeffrey A Esq",     "address": "4 B Blue Ridge Blvd",     "city": "Brighton",     "county": "Livingston",     "country": "MI",     "cypher": 48116,     "phone1": "810-292-9388",     "phone2": "810-374-9840",     "email": "josephine_darakjy@darakjy.org",     "web": "http://world wide web.chanayjeffreyaesq.com"   },   {     "first_name": "Art",     "last_name": "Venere",     "company_name": "Chemel, James 50 Cpa",     "accost": "8 West Cerritos Ave #54",     "urban center": "Bridgeport",     "county": "Gloucester",     "land": "NJ",     "zip": "08014",     "phone1": "856-636-8749",     "phone2": "856-264-4130",     "electronic mail": "art@venere.org",     "web": "http://www.chemeljameslcpa.com"   },   {     "first_name": "Lenna",     "last_name": "Paprocki",     "company_name": "Feltz Printing Service",     "address": "639 Main St",     "city": "Anchorage",     "county": "Anchorage",     "land": "AK",     "cipher": 99501,     "phone1": "907-385-4412",     "phone2": "907-921-2010",     "email": "lpaprocki@hotmail.com",     "web": "http://www.feltzprintingservice.com"   },   {     "first_name": "Donette",     "last_name": "Foller",     "company_name": "Printing Dimensions",     "address": "34 Center St",     "city": "Hamilton",     "canton": "Butler",     "state": "OH",     "nada": 45011,     "phone1": "513-570-1893",     "phone2": "513-549-4561",     "email": "donette.foller@cox.internet",     "spider web": "http://www.printingdimensions.com"   } ]

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

Client.java
parcel com.shadow.technos.javacodelib;  import com.google.gson.annotations.SerializedName;  public class Customer {      @SerializedName("first_name")     private String firstName;      @SerializedName("last_name")     individual String lastName;      @SerializedName("company_name")     private String companyName;      @SerializedName("accost")     individual String accost;      @SerializedName("urban center")     private String urban center;      @SerializedName("county")     private String county;      @SerializedName("state")     private String state;      @SerializedName("zip")     private Integer zip;      @SerializedName("phone1")     private Cord phone1;      @SerializedName("phone2")     private String phone2;      @SerializedName("electronic mail")     private String email;      @SerializedName("spider web")     private String web;      public Client() {     }      public Customer(String firstName, String lastName, String companyName, String address, String city,                     Cord county, Cord state, Integer zippo, Cord phone1, String phone2, String e-mail, String web) {         this.firstName = firstName;         this.lastName = lastName;         this.companyName = companyName;         this.address = address;         this.city = city;         this.county = county;         this.state = country;         this.zip = zip;         this.phone1 = phone1;         this.phone2 = phone2;         this.email = electronic mail;         this.spider web = web;     }      public String getFirstName() {         return firstName;     }      public void setFirstName(Cord firstName) {         this.firstName = firstName;     }      public Cord getLastName() {         return lastName;     }      public void setLastName(Cord lastName) {         this.lastName = lastName;     }      public Cord getCompanyName() {         return companyName;     }      public void setCompanyName(String companyName) {         this.companyName = companyName;     }      public String getAddress() {         return address;     }      public void setAddress(String address) {         this.accost = address;     }      public Cord getCity() {         return metropolis;     }      public void setCity(String city) {         this.city = city;     }      public String getCounty() {         return county;     }      public void setCounty(String county) {         this.county = county;     }      public String getState() {         render state;     }      public void setState(String state) {         this.state = state;     }      public Integer getZip() {         return zilch;     }      public void setZip(Integer zippo) {         this.aught = zip;     }      public Cord getPhone1() {         return phone1;     }      public void setPhone1(String phone1) {         this.phone1 = phone1;     }      public String getPhone2() {         render phone2;     }      public void setPhone2(String phone2) {         this.phone2 = phone2;     }      public String getEmail() {         return email;     }      public void setEmail(String e-mail) {         this.email = email;     }      public String getWeb() {         render web;     }      public void setWeb(String web) {         this.web = spider web;     }  }

Likewise Read: 3 useful websites for Processing JSON

Methods to Parse JSON file

Later on 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.

ane. Convert to String from Json File

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

MyClass.coffee
public class MyClass {      private static concluding String TAG = MyClass.grade.getSimpleName();     private static Gson gson;      public static void main(String[] args){          gson = new Gson();  	 	   // path of the file 	   Cord filePath = "/Users/dell/Downloads/customers_data.json"; 	 	   try{ 		// get file content as string 		Cord readJSONStr = readJSONFromFile(filePath);  		Customer[] custArray = gson.fromJson(readJSONStr, Customer[].class);  		for(Customer cust:custArray){  		    // go first_name of the file                     String first_name = cust.getFirstName();                     Organisation.out.println("first_name: "+first_name);                 } 	} catch (IOException due east) {             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()) != nada) {             stringBuilder.append(line);             stringBuilder.append(ls);         }         // delete the last new line separator         stringBuilder.deleteCharAt(stringBuilder.length() - 1);         reader.shut();         return stringBuilder.toString();     } }        

2. Parse JSON File to Model Form with Reader

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

MyClass.coffee

public class MyClass {      individual static final Cord 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"; 	 	endeavor{ 		// reader 		Reader reader = new FileReader(filePath);  		// parse JSON from file path to Customer Class 		Customer[] custArray = gson.fromJson(reader, Customer[].course);  		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) {             east.printStackTrace();         } 	     } }        

3. Parse JSON File to Model Class with JsonReader

MyClass.java
public class MyClass {      private static final String TAG = MyClass.grade.getSimpleName();     individual 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 eastward) {             e.printStackTrace();         } 	     } }        

4. Parse JSON File to Model Course with JsonElement

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

MyClass.java
public form MyClass {      private static concluding String TAG = MyClass.grade.getSimpleName();     individual static Gson gson;      public static void main(String[] args){          gson = new Gson();  	 	// path of the file 	Cord 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<json.size();iterator++){  		     // JsonElement for the JsonObject 	             JsonElement oElement=json.get(iterator);  		     // parse json chemical element to model class                      Customer cust=gson.fromJson(oElement,Customer.form);  		     // get beginning name of the parsed object                      String first_name = cust.getFirstName();                      System.out.println("first_name: "+first_name);                 }	         } catch (IOException eastward) {             e.printStackTrace();         } 	     } }        

Conclusion

Lastly, we accept 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.

krachendind.blogspot.com

Source: https://buildcoding.com/parse-json-file-with-gson-library-in-java/

0 Response to "How to Read a Json File Into a List Gson"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel