Junior — Middle
How can data in JSON format be converted into a Java object?
sobes.tech AI
Answer from AI
Libraries such as Gson or Jackson are commonly used to convert JSON into Java objects.
Example using Gson:
import com.google.gson.Gson;
class User {
String name;
int age;
}
public class JsonToObjectExample {
public static void main(String[] args) {
String json = "{\"name\": \"Ivan\", \"age\": 30}";
Gson gson = new Gson();
User user = gson.fromJson(json, User.class);
System.out.println(user.name + ", " + user.age);
}
}
In this example, the JSON string is converted into a User class object using the fromJson method. Similarly, Jackson can be used with the ObjectMapper class.