struts2的fastjson,jackson转换json简单使用

一.Fastjson使用

  1.导入fastjson.jar包

  2.对于对象

    使用JSONObject.toJSONString(对象)返回一个json对象

  3.对于集合

        使用JSONArray.toJSONString(集合对象)返回一个json对象

  4.如果对Date类型进行格式化输出

    @JSONField(format="yyyy-MM-dd")

    private Date birthday;

  5.关于属性是否生成在json串中设置

    在action中new一个SerializeFilter 

SerializeFilter filter = new PropertyFilter(){
@Override
public boolean apply(Object o, String s, Object o1) {
System.out.println(o);//要转换成json的对象
System.out.println(s);//属性的名称
System.out.println(o1);//属性值
if(o.equals("id")){
return false;//返回false代表不生成json串中
}
return true;//代表生成在json串中
}
};

二.jackson的使用
 1.导入jackson的jackson.jar包
   2.使用方法
对于对象和集合使用同样的方法
    ObjectMapper mapper = new ObjectMapper();
    Sring json = mapper.writeValueAsString(对象);
  3.处理日期类型
    ObjectMapper mapper = new ObjectMapper();
    mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd");//设置日期格式化器
    Sring json = mapper.writeValueAsString(对象);
  4.过滤属性
    1.实体类下所有的属性过滤
    在实体类中添加注解
    @JsonIgnoreProperties({"id","releaseDate"})//过滤的属性使用逗号隔开
    public class Product{
      private int id;
      private Sting name;
      private Date releaseDate;  
    }
    2.单个action的属性过滤
    @JsonFilter("productFilter")//使用注解定义过滤的实体类名
    public class Product{
      private int id;
      private Sting name;
      private Date releaseDate;  
    }
    action中编码的实现
    //FilterProvider fp = new SimpleFilterProvider().addFilter("productFilter",
    //          SimpleBeanPropertyFilter.filterOutAllExcept("id","name"));//只包含id与name
    FilterProvider fp = new SimpleFilterProvider().addFilter("productFilter",
              SimpleBeanPropertyFilter.serializeAllExcept("id","name"));//不包含id与name
    mapper.setFilters(fp);    
    
    String json = mapper.writeValueAsString(对象);
    


 

猜你喜欢

转载自www.cnblogs.com/finelee/p/9380710.html