On the previous example, How do I convert object into JSON? we convert object into JSON string. In this example you will see how to do the opposite, converting JSON string back into object.
To convert JSON string to object use Gson.fromJson()
method. This method takes the JSON string and the object type of the JSON string to be converted.
package org.kodejava.gson;
import com.google.gson.Gson;
import org.kodejava.gson.support.Student;
public class JSONToStudent {
public static void main(String[] args) {
String json = """
{
"name" : "Duke",
"address" : "Menlo Park",
"dateOfBirth" : "Feb 1, 2000 12:00:00 AM"
}
""";
Gson gson = new Gson();
Student student = gson.fromJson(json, Student.class);
System.out.println("s.getName() = " + student.getName());
System.out.println("s.getAddress() = " + student.getAddress());
System.out.println("s.getDateOfBirth() = " + student.getDateOfBirth());
}
}
This example will print the following result:
s.getName() = Duke
s.getAddress() = Menlo Park
s.getDateOfBirth() = Tue Feb 01 00:00:00 CST 2000
You can find the Student
class on the previous example, How do I convert object into JSON?.
Maven Dependencies
<!-- https://repo1.maven.org/maven2/com/google/code/gson/gson/2.9.1/gson-2.9.1.jar -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.9.1</version>
</dependency>
Latest posts by Wayan (see all)
- How do I get the number of processors available to the JVM? - March 29, 2023
- How do I show Spring transaction in log / console? - March 29, 2023
- How do I build simple search page using ZK and Spring Boot? - March 8, 2023