使用FastJson实现bean与json互转,蛇形与驼峰互转
要使用FastJson,先导入jar包或引用依赖
springboot项目引用依赖(version可以是其他版本):
1 2 3 4 5 6 | <!-- fastjson --> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.60</version> </dependency> |
如果是传统项目,下载fastjson的jar包,导入项目中。
实现bean与json的互转
注:其实fastjson中,bean是先转成str,再将str转成json。
注:具体的bean属性及赋值可见文章最后。各个bean属性见下描述:
XwRequest:priate T head,private T body;
HeadModel:retCode,retMsg,status;
UserInfo:name,phoneNo,jobName,toyList;
Toy:toyName,toyPrice;
1.将bean转为String
1 2 3 4 5 6 | // bean to String (String 是json格式) public String bean2Str(XwRequest xwRequest){ return JSON.toJSONString(xwRequest); } //结果: //{"body":{"jobName":"程序员","name":"long_tao","phoneNo":"15199999999","toyList":[{"toyName":"小汽车","toyPrice":"15.00"},{"toyName":"变形金刚","toyPrice":"35.50"}]},"head":{"retCode":"000000","retMsg":"交易成功","status":"success"}} |
这里返回的是String,如果需要return json,可以再做一次转换:
1 2 3 | public JSON str2Json(String str) { return JSON.parseObject(str); } |
2.将驼峰形式的bean转化为蛇形json
1 2 3 4 5 6 7 8 | public String bean2SXStr(XwRequest xwRequest) { // SerializeConfig config = SerializeConfigSingleton.getInstance(); SerializeConfig config = new SerializeConfig(); config.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase; return JSON.toJSONString(xwRequest, config); } //结果: //{"body":{"job_name":"程序员","name":"long_tao","phone_no":"15199999999","toy_list":[{"toy_name":"小汽车","toy_price":"15.00"},{"toy_name":"变形金刚","toy_price":"35.50"}]},"head":{"ret_code":"000000","ret_msg":"交易成功","status":"success"}} |
里面的SerializeConfigSingleton是自己写的单例,开发中建议使用单例避免性能问题
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | public class SerializeConfigSingleton { private volatile static SerializeConfig singleton; private SerializeConfigSingleton() { } public static SerializeConfig getInstance() { if (singleton == null) { synchronized (SerializeConfig.class) { if (singleton == null) { singleton = new SerializeConfig(); } } } return singleton; } } |
3.将驼峰形式的bean转化为蛇形map
1 2 3 4 5 6 7 8 9 | public Map<String, Object> bean2Map(XwRequest xwRequest) { //使用单例模式,避免性能问题 SerializeConfig config = SerializeConfigSingleton.getInstance(); config.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase; String str = JSON.toJSONString(xwRequest, config); return JSON.parseObject(str, Map.class); //结果: //{"head":{"ret_msg":"交易成功","ret_code":"000000","status":"success"},"body":{"phone_no":"15199999999","job_name":"程序员","name":"long_tao","toy_list":[{"toy_name":"小汽车","toy_price":"15.00"},{"toy_name":"变形金刚","toy_price":"35.50"}]}} } |
json.parseObject(String,Clazz);–将字符串转为bean
4.将json转为简单bean- -自动实现蛇形转驼峰
1 2 3 4 | // json的key是蛇形时,bean的属性是驼峰时,会自动转成驼峰 public XwRequest json2Bean(JSON json) { return JSON.toJavaObject(json, XwRequest.class); } |
5.将json转为嵌套对象中某个具体的bean- -自动实现蛇形转驼峰
1 2 3 4 5 6 7 | public UserInfo json2BeanUser(JSON json) { //此处获取到的json是复杂bean的json XwRequest xwRequest = JSON.toJavaObject(json, XwRequest.class); return JSON.toJavaObject(JSON.parseObject(xwRequest.getBody().toString()), UserInfo.class); //结果: //{"name":"long_tao","phoneNo":"15199999999","jobName":null,"toyList":[{"toyName":"小汽车","toyPrice":"15.00"},{"toyName":"变形金刚","toyPrice":"35.50"}]} } |
在转化的时候,出现了意外:
1.不能直接使用下列强转
1 2 3 4 | //不能实现JsonObject 转 javaBean UserInfo u1 = (UserInfo) xwRequest.getBody(); //会报错: //Exception in thread "main" java.lang.ClassCastException: com.alibaba.fastjson.JSONObject cannot be cast to FastJson.model.UserInfo |
2.json转为泛型bean时,再将bean输出,此时泛型对象内的属性还是蛇形
1 2 3 4 5 6 | public class XwRequest<T> { private T head; private T body; } //结果: //{"head":{"ret_msg":"交易成功","ret_code":"000000","status":"success"},"body":{"phone_no":"15199999999","job_mame":"程序员","name":"long_tao","toy_list":[{"toy_name":"小汽车","toy_price":"15.00"},{"toy_name":"变形金刚","toy_price":"35.50"}]}} |
附录
给XwRequest 赋值:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | public static XwRequest setRequest() { XwRequest requset = new XwRequest(); HeadModel headModel = new HeadModel(); headModel.setRetCode("000000"); headModel.setRetMsg("交易成功"); headModel.setStatus("success"); requset.setHead(headModel); UserInfo userModel = new UserInfo(); userModel.setName("long_tao"); userModel.setPhoneNo("15199999999"); userModel.setJobName("程序员"); List<Toy> toyList = new LinkedList<Toy>(); Toy toy1 = new Toy(); toy1.setToyName("小汽车"); toy1.setToyPrice("15.00"); toyList.add(toy1); Toy toy2 = new Toy(); toy2.setToyName("变形金刚"); toy2.setToyPrice("35.50"); toyList.add(toy2); userModel.setToyList(toyList); requset.setBody(userModel); return requset; } |
写在最后:
才疏学浅,若有错误的地方,欢迎大家指正。