所需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"));
}
}