Преобразование объекта Java в строку Json с помощью GSON
JSON - это обозначение объектов JavaScript . Это стандартный текстовый формат, который показывает структурированные данные на основе синтаксиса объекта JavaScript. Обычно он используется для передачи данных в веб-приложениях. JSON настоятельно рекомендуется для передачи данных между сервером и веб-приложением.
Чтобы преобразовать объект Java в JSON, можно использовать следующие методы:
- GSON: это библиотека Java с открытым исходным кодом, которая используется для сериализации и десериализации объектов Java в JSON.
- Джексон API
В этой статье объект Java преобразуется в JSON с помощью GSON:
The steps to do this are as follows:
- Add jar files of Jackson (in case of Maven project add Gson dependencies in the pom.xml file)
<dependency><groupId>com.google.code.gson</groupId><artifactId>gson</artifactId><version>2.6.2</version></dependency>Below is the screenshot showing this step:-

- Create a POJO (Plain Old Java Object) to be converted into JSON
packageGeeksforGeeks.Geeks;publicclassOrganisation {privateString organisation_name;privateString description;privateintEmployees;// Calling getters and setterspublicString getOrganisation_name(){returnorganisation_name;}publicvoidsetOrganisation_name(String organisation_name){this.organisation_name = organisation_name;}publicString getDescription(){returndescription;}publicvoidsetDescription(String description){this.description = description;}publicintgetEmployees(){returnEmployees;}publicvoidsetEmployees(intemployees){Employees = employees;}// Creating toString@OverridepublicString toString(){return"Organisation [organisation_name="+ organisation_name+", description="+ description+", Employees="+ Employees +"]";}}Below is the screenshot showing this step:-

- Create a Java class for converting the Organisation object into JSON.
packageGeeksforGeeks.Geeks;importcom.google.gson.Gson;publicclassObjectToJson {publicstaticvoidmain(String[] a){/**Creating object of Organisation **/Organisation org =newOrganisation();/** Insert the data into the object **/org = getObjectData(org);System.out.println("Json represenatation"+" of Object organisation is ");// In the below line// we have created a New Gson Object// and call it"s toJson inbuid function// and passes the object of organisationSystem.out.println(newGson().toJson(org));}/** Get the data to be inserted into the object **/publicstaticOrganisation getObjectData(Organisation org){/**insert the data**/org.setOrganisation_name("GeeksforGeeks");org.setDescription("A computer Science portal for Geeks");org.setEmployees(2000);/**Return Object**/returnorg;}}Below is the screenshot showing this step:-

- Execute the process
- Output Json
Output { "organisation_name" : "GeeksforGeeks", "description" : "A computer Science portal for Geeks", "Employee" : "2000" }
Below is the screenshot showing Output on Console:
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.