Home > Java > javaTutorial > body text

Convert JSON object to Java object using Gson library in Java?

WBOY
Release: 2023-09-18 21:29:02
forward
856 people have browsed it

Convert JSON object to Java object using Gson library in Java?

Gson is a java json library created by Google that can be used to generate JSON. By using Gson we can generate JSON and convert JSON to java object. We can call the fromJson() method of the Gson class to convert the JSON object into a Java object.

Syntax
public <T> fromJson(java.lang.String json, java.lang.Class<T> classOfT) throws JsonSyntaxException
Copy after login

Example

import com.google.gson.*;
public class JSONtoJavaObjTest {
   public static void main(String[] args) {
      Gson gson = new Gson();
      Emp emp = gson.fromJson("{&#39;name&#39;:&#39;raja&#39;,&#39;age&#39;:25}", Emp.class);
      System.out.println(emp.getName());
      System.out.println(emp.getAge());
   }
}
// Emp class<strong>
</strong>class Emp {
   String name;
   int age;
   public Emp() {
      super();
   }
   public Emp(String name, int age) {
      super();
      this.name = name;
      this.age = age;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public int getAge() {
      return age;
   }
   
   public void setAge(int age) {
      this.age = age;
   }
}
Copy after login

Output

raja
25
Copy after login

The above is the detailed content of Convert JSON object to Java object 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!