如何使用Java中的flexjson库序列化映射?
Flexjson是一个轻量级的库,用于将Java对象序列化和反序列化成JSON格式以及从JSON格式反序列化。 我们还可以使用JSONSerializer类的serialize()方法序列化Map,它对目标实例执行浅层序列化。
语法
public String serialize(Object target)
示例
import flexjson.JSONSerializer;import java.util.*;
public class JsonSerializeMapTest {
public static void main(String[] args) {
JSONSerializer serializer = new JSONSerializer().prettyPrint(true);
Student student = new Student("Adithya", "Sai", 28, "Hyderabad");
Map<String, Object> map = new HashMap<String, Object>();
map.put("Student1", "Raja");
map.put("Student2", "Ravi");
map.put("my_student", student);
String jsonStr = serializer.serialize(map);
System.out.println(jsonStr);
}
}
// Student class
class Student {
private String firstName;
private String lastName;
private int age;
private String address;
public Student() {}
public Student(String firstName, String lastName, int age, String address) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.address = address;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public int getAge() {
return age;
}
public String getAddress() {
return address;
}
public String toString() {
return "Student[ " +
"firstName = " + firstName +
", lastName = " + lastName +
", age = " + age +
", address = " + address +" ]";
}
}
输出结果
{"my_student": {
"address": "Hyderabad",
"age": 28,
"class": "Student",
"firstName": "Adithya",
"lastName": "Sai"
},
"Student1": "Raja",
"Student2": "Ravi"
}
以上是 如何使用Java中的flexjson库序列化映射? 的全部内容, 来源链接: utcz.com/z/362009.html