ObjectMapper In the Jackson library
In the Jackson library, you can use ObjectMapper
to deserialize a JSON string into a Java object. The ObjectMapper.readValue
method is commonly used for this purpose. Here's how you can do it:
Example
JSON String:
{
"name": "Alice",
"age": 25
}
Java Class:
public class Person {
private String name;
private int age;
// Getters and setters
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;
}
@Override
public String toString() {
return "Person{name='" + name + "', age=" + age + '}';
}
}
Code to Deserialize:
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonToObjectExample {
public static void main(String[] args) throws Exception {
String jsonString = "{ \"name\": \"Alice\", \"age\": 25 }";
// Create ObjectMapper instance
ObjectMapper mapper = new ObjectMapper();
// Convert JSON string to Java object
Person person = mapper.readValue(jsonString, Person.class);
// Print the object
System.out.println(person);
}
}
Output:
Person{name='Alice', age=25}
Explanation
- Define the Java Class: Ensure the class has fields matching the JSON structure. Include getters, setters, and optionally
toString
for easy debugging. - Use
readValue
: Callmapper.readValue(jsonString, Person.class)
to map the JSON string to the Java object. - ObjectMapper: This is the primary class in Jackson for converting between JSON and Java objects.
Additional Notes
- Customizing Field Names: If JSON field names differ from Java field names, use the
@JsonProperty
annotation.public class Person { @JsonProperty("full_name") private String name; // Rest of the class... }
- Handling Collections: Use a
TypeReference
when deserializing lists or maps.List<Person> people = mapper.readValue(jsonArrayString, new TypeReference<List<Person>>() {});
댓글
댓글 쓰기