How to convert the following json string to java object?
To convert a JSON string to a Java object, you can use the fromJson
method of the Gson
class.
Here's an example of how you can use the fromJson
method to convert a JSON string to a Java object:
import com.google.gson.Gson;
public class Main {
public static void main(String[] args) {
String json = "{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}";
Gson gson = new Gson();
Person person = gson.fromJson(json, Person.class);
System.out.println(person);
}
}
class Person {
private String name;
private int age;
private String city;
// getters and setters
}
This code defines a Person
class with three fields: name
, age
, and city
. It also defines a main
method that creates a JSON string representing a person and uses the Gson
class to convert the JSON string to a Person
object. The resulting Person
object is then printed to the console.
To use this code, you will need to add the Gson library to your project. You can do this by adding the following dependency to your build.gradle
file:
dependencies {
implementation 'com.google.code.gson:gson:2.8.6'
}
I hope this helps! Let me know if you have any questions.