JSONObject、JSONArray、xml的常用操作
1.JSONObject的操作
创建JSONObject
JSONObject ob = new JSONObject();
ob.put("busiCd", "111");
ob.put("channel_cd", "1000000001");
解析JSONObject
TestModel model = new TestModel();// 声明一个对象对应json里面的key
String info = "{'busiCd':'111','channel_cd':'1000000001'}";
JSONObject sobj = JSONObject.fromObject(info);// 将info转换为JSONObject
// 1.1、单个获得,用key得到对象值
String result = sobj.getString("busiCd");
String code = sobj.getString("channel_cd");
// 1.2、转对象,直接将json对象转换为model
model = (TestModel) JSONObject.toBean(sobj, TestModel.class);
// 1.3、遍历对象,循环获得
Iterator<String> it = sobj.keys();
while (it.hasNext()) {
String key = it.next();
System.out.println(key + ":" + sobj.get(key));
}
2.JSONArray的操作
创建JSONArray
List<TestModel> testModels = new ArrayList<TestModel>();//数据源
JSONArray ja = new JSONArray();// 调用接口计算扣企业的钱和个人的钱
for (int i = 0; i < testModels.size(); i++) {
JSONObject ob = new JSONObject();
ob.put("productCd", testModels.get(i).getBusiCd());
ob.put("counts", testModels.get(i).getChannel_cd());
ja.add(ob);
}
解析JSONArray
List<TestModel> models = new ArrayList<TestModel>();// 声明一个对象对应json里面的key
String info = "[{'busiCd':'111','channel_cd':'1000000001'}]";
JSONArray array = JSONArray.fromObject(info);
// 2.1 使用toList方法转数组
models = JSONArray.toList(array, TestModel.class);
// 2.2 使用toCollection转数组
models = (List<TestModel>) JSONArray.toCollection(array,TestModel.class);
// 2.3 遍历对象,循环获得
Iterator<JSONObject> its = array.iterator();
while (its.hasNext()) {
JSONObject obj = its.next();
Iterator<String> ite = obj.keys();
while (ite.hasNext()) {
String key = ite.next();
System.out.println(key + ":" + obj.get(key));
}
}
3、xml操作
解析xml
// 3.1解析xml格式的数据
String xmlStr = "<rsp><rsp_cd>0000</rsp_cd><tx_type>PY41</tx_type></rsp>";
// 将xml格式的字符串转换成Document对象
Document doc = DocumentHelper.parseText(xmlStr);
// 获取根节点
org.dom4j.Element root = doc.getRootElement();
// 获取根节点下的所有元素
List children = root.elements();
// 循环所有子元素
if (children != null && children.size() > 0) {
for (int i = 0; i < children.size(); i++) {
Element child = (Element) children.get(i);
if ("rsp_cd".equals(child.getName())) {
System.out.println("rsp_cd:" + child.getTextTrim());
}
if ("tx_type".equals(child.getName())) {
System.out.println("tx_type:" + child.getTextTrim());
}
}
}