如何在Java中使用flexjson将JSON反序列化为Java对象?
该Flexjson 是一个轻量级 的库序列化 和反序列化 Java对象和从JSON格式允许两个对象的深与浅拷贝。为了使用flexjon运行Java程序,我们需要导入一个flexjson 包。我们可以使用JSONDeserializer类的deserialize ()方法将JSON反序列化为Java对象,它将JSON字符串作为输入,并从该JSON表示形式生成静态类型的对象图。默认情况下,它使用json数据中的class属性,以将未类型化的通用json数据映射到特定的Java类型。
语法
public T deserialize(String input)
在下面的程序中,将JSON反序列化为Java对象
示例
import flexjson.*;public class DeserializeJSONTest {
public static void main(String[] args) {
JSONDeserializer<Student> deserializer = new JSONDeserializer<Student>();
String jsonStr =
"{" +
"\"firstName\": \"Ravi\"," +
"\"lastName\": \"Chandra\"," +
"\"age\": 35," + "\"class\": \"Student\"," + "\"salary\": 50000.00," +
"}";
Student student = deserializer.deserialize(jsonStr);
System.out.println(student);
}
}
// Student classclass Student {
private String firstName;
private String lastName;
private int age;
private double salary;
public Student() {}
public Student(String firstName, String lastName, int age, double salary) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.salary = salary;
}
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 int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public String toString() {
return "Student[ " +
"firstName = " + firstName +
", lastName = " + lastName +
", age = " + age +
", salary = " + salary +
" ]";
}
}
输出结果
Student[ firstName = Ravi, lastName = Chandra, age = 35, salary = 50000.0 ]
以上是 如何在Java中使用flexjson将JSON反序列化为Java对象? 的全部内容, 来源链接: utcz.com/z/331419.html