Java中Json格式数据的应用
}
public void setString(String string) {
this.string = string;
}
@Override
public String toString() {
return "BeanA{"bool=" + bool +", integer=" + integer +", string='" + string + '\'' +"}";
}
}
4.JSON串-->XML
public static void test4() {
System.out.println("------------JSON串-->XML----------");
JSONObject json = new JSONObject(true);
String xml = new XMLSerializer().write(json);
System.out.println(xml);
JSONObject json1 = JSONObject.fromObject("{\"name\":\"json\",\"bool\":true,\"int\":1}");
String xml1 = new XMLSerializer().write(json1);
System.out.println(xml1);
JSONArray json2 = JSONArray.fromObject("[1,2,3]");
String xml2 = new XMLSerializer().write(json2);
System.out.println(xml2);
}
5.XML-->JSON串
public static void test5() {
System.out.println("------------XML-->JSON串----------");
String xml = "" +
"<a class=\"array\">\n" +
" <e type=\"function\" params=\"i,j\">\n" +
" return matrix[i][j];\n" +
" </e>\n" +
"</a>";
JSONArray json = (JSONArray) new XMLSerializer().read(xml);
System.out.println(json);
}
特别注意:
1、所有的Bean都应该定义为public,否则会出现net.sf.json.JSONException: java.lang.NoSuchMethodException: Property '***' has no getter method的错误。
2、必须引入xom-1.1.jar包,否则抛出java.lang.NoClassDefFoundError: nu/xom/Serializer