项目中前后端分离,采用json数据交互。fastjson 默认对枚举的处理达不到项目需求
例如代码中有个城市的枚举
SHANGHAI( "上海","SHANGHAI","上海",true,"SH","shanghai.qfang.com",DataSourceEnum.SHANGHAI,"121.480263","31.236295")
默认序列化的时候是SHANGHAI 而有时候想要得到枚举的其他属性比如上海这种中文
想到的方法是利用fastjson的SerializeConfig处理 利用反射机制得到相应属性
写了一般测试没问题,发现一个问题有时候枚举序列化不成功,项目经理帮忙解决了这个问题
少了一段代码
config.put(Person.class,new JavaBeanSerializer(Person.class));
贴上代码
package com.xyw.test; import java.io.IOException; import java.lang.reflect.Method; import java.lang.reflect.Type; import com.alibaba.fastjson.serializer.EnumSerializer; import com.alibaba.fastjson.serializer.JSONSerializer; import com.alibaba.fastjson.serializer.SerializeWriter; /** * 使用方法 * config.put(PoJo.class,new JavaBeanSerializer(PoJo.class)); * 参数一是你的枚举类型,参数二是待输出的值(数组) * config.put(YourEnum.class,new EnumCnSerializer(YourEnum.class,"desc")); * @param <T> */ @SuppressWarnings("rawtypes") public class EnumCnSerializer<T extends Enum> extends EnumSerializer{ private Class<T> clazz; private String[] proptertiesName; public EnumCnSerializer(Class<T> clazz,String ... proptertiesName) { super(); this.clazz = clazz; this.proptertiesName = proptertiesName; } @Override public void write(JSONSerializer serializer,Object object,Object fieldName,Type fieldType) throws IOException { SerializeWriter out = serializer.getWriter(); if (object == null) { serializer.getWriter().writeNull(); return; } T e = clazz.cast(object) ; serializer.write(e.name()); if(proptertiesName==null){ return; } for(String propertyName:proptertiesName){ propertyName = propertyName.substring(0,1).toUpperCase()+propertyName.substring(1); try { Method method = clazz.getMethod("get" + propertyName); if(fieldName instanceof Integer){ out.write(","); serializer.write(method.invoke(e)); }else{ out.write(","); serializer.write(fieldName + propertyName); out.write(":"); serializer.write(method.invoke(e)); } } catch (Exception e1) { return; } } } }
package com.xyw.test; import java.util.ArrayList; import java.util.List; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.serializer.JavaBeanSerializer; import com.alibaba.fastjson.serializer.SerializeConfig; import com.xyw.entity.Person; public class Test3 { /** * @param args */ public static void main(String[] args) { Person p = new Person("ZS",CityEnum.SHANGHAI); String result = JSON.toJSONString(p); System.out.println(result); System.out.println("----------------"); SerializeConfig config = new SerializeConfig(); config.put(Person.class,new JavaBeanSerializer(Person.class)); config.put(CityEnum.class,new EnumCnSerializer(CityEnum.class,"cityName","domain")); result = JSON.toJSONString(p,config); System.out.println(result); List list = new ArrayList(); list.add(p); result = JSON.toJSONString(list,config); System.out.println(result); } }
输出结果
{"city":"SHANGHAI","name":"ZS"} ---------------- {"city":"SHANGHAI","cityCityName":"上海","cityDomain":"shanghai.qfang.com","name":"ZS"} [{"city":"SHANGHAI","name":"ZS"}]