您的位置:首页 > 编程语言 > Java开发

java 对象转 json 和 xml

2013-11-01 10:36 246 查看
 所需jar包 json.jar , jsonplugin.jar , commons-logging.jar 

代码是可以运行的

import org.json.JSONException;
import org.json.JSONObject;
import org.json.XML;

import com.googlecode.jsonplugin.JSONExeption;
import com.googlecode.jsonplugin.JSONUtil;
/**
* 功能说明: java 对象转json , xml
*
*
*/
public class ConvertXMLandJSON {

public static String convert(Object object, String returnType) throws Exception{
String returnStr = "";
try {
if("json".equals(returnType)){
returnStr=new JSONObject(JSONUtil.serialize(object)).toString(4);
}if("xml".equals(returnType)){
String xmlHead = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
returnStr=xmlHead+"<result>"+XML.toString(new JSONObject(JSONUtil.serialize(object)))+"</result>";
}
} catch (JSONException e) {
e.printStackTrace();
throw e;
} catch (JSONExeption e) {
e.printStackTrace();
}
return returnStr;
}

public static void main(String[] args) throws Exception{

Person p = new Person("张三", "男", 19);
System.out.println(ConvertXMLandJSON.convert(p, "json"));
System.out.println(ConvertXMLandJSON.convert(p, "xml"));

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  json xml 转xml 转json