Java中使用Jackson库将JSON转换为Object
ObjectMapper类是Jackson库中最重要的类。 我们可以使用ObjectMapper类的readValue()方法将JSON转换为Java Object,此方法从给定的JSON内容String反序列化JSON内容。
语法
public <T> readValue(String content, JavaType valueType) throws IOException, JsonParseException, JsonMappingException
示例
import java.io.*;import java.util.*;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.*;
public class JSONToJavaObjectTest {
public static void main(String args[]) throws JsonGenerationException, JsonMappingException, IOException {
Employee emp1 = new Employee();
emp1.setFirstName("Raja");
emp1.setLastName("Ramesh");
emp1.setId(115);
emp1.getTechnologies().add("Java");
emp1.getTechnologies().add("Selenium");
emp1.getTechnologies().add("Spark");
ObjectMapper mapper = new ObjectMapper();
String jsonStr = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(emp1);
System.out.println(jsonStr);
System.out.println("将JSON反序列化为对象:");
Employee emp2 = mapper.readValue(jsonStr, Employee.class);
System.out.println(emp2.getId() + " " + emp2.getFirstName() + " " + emp2.getLastName() + " " + emp2.getTechnologies());
}
}
// Employee类
class Employee {
private int id;
private String firstName;
private String lastName;
private List technologies = new ArrayList<>();
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public List getTechnologies() {
return technologies;
}
public void setTechnologies(List technologies) {
this.technologies = technologies;
}
}
输出结果
{"id" : 115,
"firstName" : "Raja",
"lastName" : "Ramesh",
"technologies" : [ "Java", "Selenium", "Spark" ]
}
将JSON反序列化为对象:
115 Raja Ramesh [Java, Selenium, Spark]
以上是 Java中使用Jackson库将JSON转换为Object 的全部内容, 来源链接: utcz.com/z/351578.html