美文网首页
2、fastjson使用

2、fastjson使用

作者: 小manong | 来源:发表于2018-09-21 23:46 被阅读0次

一、fastjson常用使用

  • fastjson的序列化和反序列化都不需要做特别配置,唯一的要求是,你序列化的类符合java bean规范。
  • fastjson常用api:
// 把JSON文本parse为JSONObject或者JSONArray 
public static final Object parse(String text); 
// 把JSON文本parse成JSONObject    
public static final JSONObject parseObject(String text); 
// 把JSON文本parse为JavaBean 
public static final <T> T parseObject(String text, Class<T> clazz); 
// 把JSON文本parse成JSONArray 
public static final JSONArray parseArray(String text); 
//把JSON文本parse成JavaBean集合 
public static final <T> List<T> parseArray(String text, Class<T> clazz); 
 // 将JavaBean序列化为JSON文本 
public static final String toJSONString(Object object);
// 将JavaBean序列化为带格式的JSON文本 
public static final String toJSONString(Object object, boolean prettyFormat); 
//将JavaBean转换为JSONObject或者JSONArray。
public static final Object toJSON(Object javaObject); 

1、javaBean之间的转换

(1)javaBean序列化为string

String jsonString = JSON.toJSONString(person);

(2)javaBean反序列化

person =JSON.parseObject(jsonString,Person.class);

2、List<javaBean>之间的转换
(1)序列化

List<Person> persons = new ArrayList<Person>();
String jsonString = JSON.toJSONString(persons);

(2)反序列化

  • 比如使用redis存zsort的时候,范围取出时候就是一个列表

List<Person> persons2 = JSON.parseArray(jsonString,Person.class);

二、fastjson订制序列化

  • fastjson通过通过@JSONField、@JSONType、SerializeFilter等注解参数进行定制序列化
    (1)属性和方法上使用@JSONField
//配置序列化的时候,不序列化id 
@JSONField(serialize=false) 
private int id; 
private int age; //年龄 
// 配置序列化的名称 
@JSONField(name="gender") 
public String sex;

(2)在类上使用@JSONType

//配置序列化的时候,不序列化id  sex
@JSONType(ignores ={"id", "sex"}) 
public class Uoimplements Serializable {}
// 配置序列化的时候,序列化name 和sex
@JSONType(includes={"name","sex"}) 
public class Uo1implements Serializable {}

(3)使用SerializeFilter定制序列化:

  • 通过SerializeFilter可以使用扩展编程的方式实现定制序列化。fastjson提供了多种SerializeFilter。

三、fastjson常见问题

1、序列化的类必须有一个无参构造方法
否则会报错
Exception in thread "main" com.alibaba.fastjson.JSONException: default constructor not found. class
2、避免子类重写父类成员变量,有可能报错
3、不要在以is为开头命名属性,fastjson在解析时候会将is去掉

相关文章

网友评论

      本文标题:2、fastjson使用

      本文链接:https://www.haomeiwen.com/subject/dpinnftx.html