Home>Article>Java> How to convert Java objects to JSON

How to convert Java objects to JSON

王林
王林 forward
2023-05-14 09:37:05 3350browse

In this code snippet, we do the following:

  • Create aStudentobject and set its properties using the setter method.

  • CreateJSONObjectCallobjectand use theStudentobject as a parameter to its constructor.

  • #JSONObjectUse the getter method to generate a JSON string.

  • Call theobject.toString()method to obtain the JSON string.

import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.gson.Gson; import org.json.JSONObject; import java.util.Arrays; public class PojoToJSON { public static void main(String[] args) throws JsonProcessingException { Student student = new Student(); student.setId(1L); student.setName("Alice"); student.setAge(20); student.setCourses(Arrays.asList("Engineering", "Finance", "Chemistry")); JSONObject object = new JSONObject(student); String json = object.toString(); System.out.println(json); System.out.println(new Gson().toJson(student)); // Creating Object of ObjectMapper define in Jackson API ObjectMapper Obj = new ObjectMapper(); // Converting the Java object into a JSON string String jsonStr = Obj.writeValueAsString(student); // Displaying Java object into a JSON string System.out.println(jsonStr); } }

Running this code produces the following results:

##{"courses":["Engineering","Finance", "Chemistry"],"name":"Alice","id":1,"age":20}

{"id":1,"name":"Alice","age":20," courses":["Engineering","Finance","Chemistry"]}
{"id":1,"name":"Alice","age":20,"courses":["Engineering", "Finance","Chemistry"]}

Student class used in the above code:

import java.util.List; public class Student { private Long id; private String name; private int age; private List courses; public Student(Long id, String name, int age, List courses) { this.id = id; this.name = name; this.age = age; this.courses = courses; } Student() { } public Long getId() { return id; } public void setId(Long id) { this.id = id; } 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; } public List getCourses() { return courses; } public void setCourses(List courses) { this.courses = courses; } }

Maven dependencies

  4.0.0 com.example.javaobjectjson JavaObjectJSON 1.0-SNAPSHOT    org.json json 20211205    com.google.code.gson gson 2.9.0   com.fasterxml.jackson.core jackson-databind 2.12.1   

The above is the detailed content of How to convert Java objects to JSON. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete