转载:FastJson实现bean与json互转,蛇形与驼峰互转 | 码农家园
要使用FastJson,先导入jar包或引用依赖
<!-- fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.60</version>
</dependency>
实现bean与json的互转
注:其实fastjson中,bean是先转成str,再将str转成json。
1.将bean转为String
// 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,可以再做一次转换:
public JSON str2Json(String str) {
return JSON.parseObject(str);
}
2.将驼峰形式的bean转化为蛇形json
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是自己写的单例,开发中建议使用单例避免性能问题
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
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- -自动实现蛇形转驼峰
// json的key是蛇形时,bean的属性是驼峰时,会自动转成驼峰
public XwRequest json2Bean(JSON json) {
return JSON.toJavaObject(json, XwRequest.class);
}
5.将json转为嵌套对象中某个具体的bean- -自动实现蛇形转驼峰
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"}]}
}