日期:2014-05-16  浏览次数:20330 次

Bean 2 JSON USING XSTREAM

项目上一直要使用JDK1.4.2,所以选择bean to json的工具收到很大限制,找了gson 和 jackson flexson好像都要求jdk1.5+ ,xstream好像还满足要求,就是包太大了。

?

	public static void main(String[] args) {
		A a= new A();
		XStream xstream = new XStream(new JsonHierarchicalStreamDriver() {
		    public HierarchicalStreamWriter createWriter(Writer writer) {
		        return new JsonWriter(writer, JsonWriter.DROP_ROOT_MODE);
		    }
		});
        xstream.setMode(XStream.NO_REFERENCES);
        xstream.alias("product", A.class);

        System.out.println(xstream.toXML(a));
	}

?? 结果

??{

  "s1": "a",
  "s2": "bb",
  "b": {
    "b1": "b1",
    "b2": "2010-03-24"
  },
  "itemList": [
    {
      "b1": "b1",
      "b2": "2010-03-24"
    },
    {
      "b1": "b1",
      "b2": "2010-03-24"
    }
  ]
}

?

感觉相对还比较方便