在我们Java开发 接口调试过程中 经常会遇到 实体转换长json、xml 或者json 转换成实体、xml 等多种情况,今天博主给大家详细举例:
1、原生实体与json 相互转换:
User user = new User();
HashMap paramMap = new HashMap();
String requestString = JSON.toJSONString(paramMap);
ReturnInfo returnInfo = JSON.parseObject(result, ReturnInfo.class);//
result 字符串为json retrunInfo.class 为实体类
2、
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
/**
* JSOn工具类
*/
@SuppressWarnings("unchecked")
public class JSONUtils {
/**
* 生成json数组
* @param datasJSON
* @return
*/
public static JSONArray createJSONArray(String datasJSON){
String datas = JSONUtils.json2String(datasJSON, "datas");
JSONArray results = new JSONArray();;
JSONArray datasJSONArray = JSONArray.fromObject(datas);
Iterator iterator = datasJSONArray.iterator();
while(iterator.hasNext()){
JSONObject data = (JSONObject) iterator.next();
JSONObject eachDataObject = data.getJSONObject("data");
results.element(eachDataObject);
}
return results;
}
/**
* 生成jsonobject
* @param datasJSON
* @return
*/
@SuppressWarnings("rawtypes")
public static List createJSONObjects(String datasJSON){
List results = new ArrayList();
String datas = JSONUtils.json2String(datasJSON, "datas");
JSONArray jsonArray = JSONArray.fromObject(datas);
Iterator iterator = jsonArray.iterator();
while(iterator.hasNext()){
JSONObject data = (JSONObject) iterator.next();
JSONObject eachDataObject = data.getJSONObject("data");
results.add(eachDataObject);
}
return results;
}
/**
* 另一种生成jsonObject 方法
* @param datasJSON
* @return
*/
@SuppressWarnings("rawtypes")
public static JSONObject createJSONObject(String datasJSON){
JSONObject result = new JSONObject();
String datas = JSONUtils.json2String(datasJSON, "datas");
JSONArray jsonArray = JSONArray.fromObject(datas);
Iterator iterator = jsonArray.iterator();
while(iterator.hasNext()){
JSONObject data = (JSONObject) iterator.next();
JSONObject eachDataObject = data.getJSONObject("data");
result = eachDataObject;
}
return result;
}
/**
* json转换成list
* @param json the json
* @return List
日常开发常用json转换 工具类:比如
Result info = (Result) JSONUtils.jsonToObject(result,Result.class);//json转实体
String bean2json = JSONUtils.beanTojson(map);//实体转json
3、xml转换相关
String str=xml+XmlUtils.toXml(packet);
xml工具类:
import java.io.File;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.jingyou.application.cases.dto.custom.mps.MPSMainInfoDTO;
import com.jingyou.application.cases.dto.custom.mps.QueryConditionDTO;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.DomDriver;
/**
*
* ClassName:SerializeUtils Reason: 基于xstream的xml序列化工具类
*/
@SuppressWarnings("unchecked")
public class XmlUtils {
private static XStream getXStream(Class clazz) {
// dom方式解析
XStream xstream = new XStream();
// 开启注解检查,指定注解类
xstream.processAnnotations(clazz);
// 注册日期对象的转换器
xstream.registerConverter(new Converter() {
// Date → String
public void marshal(Object arg0, HierarchicalStreamWriter arg1, MarshallingContext arg2) {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
arg1.setValue(dateFormat.format((Date) arg0));
}
// String → Date
public Object unmarshal(HierarchicalStreamReader arg0, UnmarshallingContext arg1) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
if(!"".equals(arg0.getValue())){
if(arg0.getValue().length() < 19){
dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
}
if(arg0.getValue().length() < 11){
dateFormat = new SimpleDateFormat("yyyy-MM-dd");
}
try {
return dateFormat.parse(arg0.getValue());
} catch (ParseException e) {
e.printStackTrace();
throw new RuntimeException(e.getCause());
}
}else{
return null;
}
}
// 对Date类型转换
public boolean canConvert(Class arg0) {
return arg0.equals(Date.class);
}
});
return xstream;
}
private static XStream getXStreamNew(Class clazz, String aliasName) {
// dom方式解析
XStream xstream = new XStream();
// 动态修改类注解
if(aliasName != null && !"".equals(aliasName)){
xstream.alias(aliasName, clazz);
}
// 开启注解检查,指定注解类
xstream.processAnnotations(clazz);
// 注册日期对象的转换器
xstream.registerConverter(new Converter() {
// Date → String
public void marshal(Object arg0, HierarchicalStreamWriter arg1, MarshallingContext arg2) {
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
arg1.setValue(dateFormat.format((Date) arg0));
}
// String → Date
public Object unmarshal(HierarchicalStreamReader arg0, UnmarshallingContext arg1) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
if(!"".equals(arg0.getValue())){
if(arg0.getValue().length() < 19){
dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
}
if(arg0.getValue().length() < 11){
dateFormat = new SimpleDateFormat("yyyy-MM-dd");
}
try {
return dateFormat.parse(arg0.getValue());
} catch (ParseException e) {
e.printStackTrace();
throw new RuntimeException(e.getCause());
}
}else{
return null;
}
}
// 对Date类型转换
public boolean canConvert(Class arg0) {
return arg0.equals(Date.class);
}
});
return xstream;
}
public static String toXml(Object obj) {
String xml = getXStream(obj.getClass()).toXML(obj);
xml = xml.replaceAll("__", "_"); // xstream的bug,应避免使用下划线作为连接符
return xml;
}
public static String toXmlNew(Object obj, String aliasName){
String xml = getXStreamNew(obj.getClass(), aliasName).toXML(obj);
xml = xml.replaceAll("__", "_"); // xstream的bug,应避免使用下划线作为连接符
return xml;
}
public static T fromXmlNew(String xml, Class clazz, String aliasName) {
T t = (T) getXStreamNew(clazz, aliasName).fromXML(xml);
return t;
}
public static T fromXml(String xml, Class clazz) {
T t = (T) getXStream(clazz).fromXML(xml);
return t;
}
public static T fromXml(File xml, Class clazz) {
T t = (T) getXStream(clazz).fromXML(xml);
return t;
}
public static T fromXml(InputStream xml, Class clazz) {
T t = (T) getXStream(clazz).fromXML(xml);
return t;
}
}
java开发中肯定有所帮助,如果有疑问可以留言:我会及时帮你解决