该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 deserializer = new JSONDeserializer();
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 ]