fastjson基础
导包
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.1.43</version>
</dependency>
实体类
/**
* 就三个演示字段,省略get set 法 toString
*/
public class Stu {
private String name;
// 年龄
private String age;
// 住址
private String address;
...
与map相互转化
Map<String, Object> map = new HashMap<String, Object>();
map.put("sno", 1002);
map.put("name", "李四");
map.put("age", 32);
//将参数map集合中的映射关系转存到JSONObject中
String s = JSONObject.toJSONString(map);
System.out.println(s);
Map<String, Object> map1= (Map<String, Object>) JSONObject.parse(s);
for (Map.Entry<String, Object> entry : map1.entrySet()) {
System.out.println("key= " + entry.getKey() + " and value= "
+ entry.getValue());
}
与list相互转化
Stu stu = new Stu("王五", "23", "45");
String str = JSONObject.toJSONString(stu);
System.out.println(str);
JSONObject jsonObject =new JSONObject().parseObject(str);
Stu stu1 =new JSONObject().parseObject(str, Stu.class);
System.out.println(stu1);
与javabean相互转化
Stu stu = new Stu("王五", "23", "45");
String str = JSONObject.toJSONString(stu);
System.out.println(str);
JSONObject jsonObject =new JSONObject().parseObject(str);
Stu stu1 =new JSONObject().parseObject(str, Stu.class);
System.out.println(stu1);
二、beanToMap
实体
public class Stu {
private int id ;
private String name;
private String pass;
private BigDecimal age;
private List<String> aa;
private List<Teacher> teacherlist;
。。。。。省略get set toString
}
public class Teacher {
private int id;
private String name;
private String curse;
。。。。。省略get set toString
}
beantomap
public static Map<String, Object> transBean2Map(Object obj) {
if (obj == null) {
return null;
}
Map<String, Object> map = new HashMap<String, Object>();
try {
BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor property : propertyDescriptors) {
String key = property.getName();
// 过滤class属性
if (!key.equals("class")) {
// 得到property对应的getter方法
Method getter = property.getReadMethod();
Object value = getter.invoke(obj);
map.put(key, value);
}
}
} catch (Exception e) {
System.out.println("transBean2Map Error " + e);
}
return map;
}