Home > Java > javaTutorial > Convert list of objects to JSON using Gson library in Java

Convert list of objects to JSON using Gson library in Java

PHPz
Release: 2023-09-22 09:41:09
forward
969 people have browsed it

Convert list of objects to JSON using Gson library in Java

Gson is a library that can be used to convert Java objects into JSON representations. It can also be used to convert JSON strings into equivalent Java objects. The main class to use is Gson, which we can create by calling new Gson(), and the GsonBuilder class can be used to create GsonExample.

We can convert the list of objects by first creating a Person class and then JSON formatting the list of Person objects.

Example

import java.util.*;
import java.util.stream.*;
import com.google.gson.*;
public class JSONConverterTest {
   public static void main( String[] args ) {
      Gson gson = new GsonBuilder().setPrettyPrinting().create();
      List list = Stream.of(new Person("Raja", "Ramesh", 30, "9959984800"),
                            new Person("Jai", "Dev", 25, "7702144400"),
                            new Person("Adithya", "Sai", 21, "7013536200"),
                            new Person("Chaitanya", "Sai", 28, "9656444150"))
                            .collect(Collectors.toList());
      System.out.println("Convert list of person objects to Json:");
      String json = gson.toJson(list); // converts to json
      System.out.println(json);
   }
}
// Person class<strong>
</strong>class Person {
   private String firstName, lastName, contact;
   private int age;
   public Person(String firstName, String lastName, int age, String contact) {
      this.firstName = firstName;
      this.lastName = lastName;
      this.age = age;
      this.contact = contact;
   }
   public String toString() {
      return "[" + firstName + " " + lastName + " " + age + " " +contact +"]";
   }
}
Copy after login

Output

Convert list of person objects to Json:
[
{
   "firstName": "Raja",
   "lastName": "Ramesh",
   "contact": "9959984800",
   "age": 30
},
{
   "firstName": "Jai",
   "lastName": "Dev",
   "contact": "7702144400",
   "age": 25
},
{
   "firstName": "Adithya",
   "lastName": "Sai",
   "contact": "7013536200",
   "age": 21
},
{
   "firstName": "Chaitanya",
   "lastName": "Sai",
   "contact": "9656444150",
   "age": 28
}
]
Copy after login

The above is the detailed content of Convert list of objects to JSON using Gson library in Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template