xml 和 json 转换工具 不指定

Heck post in 编程杂谈 2010/11/06 19:08 评论(0) 阅读(1684) | |
         前几天在书上看的,实验了一下,结果还不错,收藏下来:
package com;
import java.util.*;

import net.sf.json.JSONObject;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

public class ExtHelper {
  public static String getXmlFormList(long recordTotal,List beanList){
    Total total = new Total(); //保存记录总数
    total.setResults(recordTotal); //设置记录总数到 total对象
    List results = new ArrayList(); //创建临时的 List 对象 results
    results.add(total); // 添加对象
    results.addAll(beanList); // 追加对象
    XStream sm = new XStream(new DomDriver()); //创建Xstream对象
    for(int i=0;i<results.size();i++){
      Class c = results.get(i).getClass();
      String b = c.getName();
      String[] temp = b.split("\\.");
      sm.alias(temp[temp.length-1],c);
    }
    String xml = "<?xml version='1.0' encoding='UTF-8'?>"+sm.toXML(results);
    return xml;
  }

  
  public static String getJsonFromList(long recordTotal,List beanList){
    TotalJson total = new TotalJson();
    total.setResults(recordTotal);
    total.setItems(beanList);
    JSONObject jsonArray = JSONObject.fromObject(total);
    return jsonArray.toString();
  }
}



下面提供的是所需要的jar包下载:


来源:Heck's Blog
地址:http://www.hecks.tk/xml-and-json-convert-helper-html/
转载时须以链接形式注明作者和原始出处及本声明,否则将追究法律责任,谢谢配合!
Tags: , ,