
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库序列化一个map?的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号