能够很好的支持复杂对象序列化和反序列化的json工具有阿里巴巴的fastjson和Google的gson,但是两个还不一样。gson参见:http://blog.csdn.net/lk_blog/article/details/7685210
下面是我对fastjson针对map类型的简单测试结果:
package com.yjl.javabase.json;
import com.alibaba.fastjson.JSON;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class FastJsonTest {
public static void main(String[] args) {
Map<String, Student> stringStudentMap = new HashMap<>();
Student s1 = new Student(11, "aaa", "bbb", 111.111, new Date());
Student s2 = new Student(22, "cccc", "ddddd", 222.222, new Date());
stringStudentMap.put("one", s1);
stringStudentMap.put("tow", s2);
System.out.println(JSON.toJSONString(stringStudentMap));
System.out.println();
Map<Student, String> studentStringMap = new HashMap<>();
studentStringMap.put(s1, "three");
studentStringMap.put(s2, "four");
System.out.println(JSON.toJSONString(studentStringMap));
}
}
class Student {
private int age;
private String firstName;
private String lastName;
private double heigth;
private Date birth;
public Student(int age, String firstName, String lastName, double heigth, Date birth) {
this.age = age;
this.firstName = firstName;
this.lastName = lastName;
this.heigth = heigth;
this.birth = birth;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
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 double getHeigth() {
return heigth;
}
public void setHeigth(double heigth) {
this.heigth = heigth;
}
}
{"one":{"age":11,"birth":1486782339687,"firstName":"aaa","heigth":111.111,"lastName":"bbb"},"tow":{"age":22,"birth":1486782339687,"firstName":"cccc","heigth":222.222,"lastName":"ddddd"}}
{{"age":11,"birth":1486782339687,"firstName":"aaa","heigth":111.111,"lastName":"bbb"}:"three",{"age":22,"birth":1486782339687,"firstName":"cccc","heigth":222.222,"lastName":"ddddd"}:"four"}
当map的key是实体类的时候出来的结果不是标准的json,而gson使用数组表示的。