android 创建复杂json格式文件代码思路。在设计json数据hashmap数据的时候添加标记位。如生成单个json数据,则标记位位single,如需json数组长度大于1 则标记位位multi.
并且次吃的json数组名相同。
/**
* 创建混合json数据代码
* @param mList
* @return
* @throws JSONException
*/
public static JSONObject createJsonDate(List<HashMap> mList)
throws JSONException {
// 声明json对象
if (mList.isEmpty()) {
Log.d(AutoReportUtil.TAG, "mList is empty");
return null;
}
JSONArray jsonArray2 = new JSONArray();
String jsonName = "";
String jsonNameMuiti = "";
JSONObject outData = new JSONObject();
for (int i = 0; i < mList.size(); i++) {
HashMap<String, String> map = mList.get(i);
if (map != null) {
if (map.get("sign").equals("single")) { //单独的数组
map.remove("sign");
JSONArray jsonArray = new JSONArray();
JSONObject node = new JSONObject();
Iterator<?> iter = map.entrySet().iterator();
while (iter.hasNext()) {
@SuppressWarnings("rawtypes")
Map.Entry entry = (Map.Entry) iter.next();
if (!entry.getKey().equals("arrayName")) {
node.put((String) entry.getKey(), entry.getValue());
} else {
jsonName = (String) entry.getValue();
}
}
jsonArray.put(node);
outData.put(jsonName, jsonArray);
} else if (map.get("sign").equals("muiti")) { //复杂的数据
JSONObject node = new JSONObject();
Iterator<?> iter = map.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
if (entry.getKey().equals("arrayName")) {//过滤数组名
jsonNameMuiti = (String) entry.getValue();
} else if (entry.getKey().equals("sign")) { //过滤标签
//
} else {
node.put((String) entry.getKey(), entry.getValue());
}
}
jsonArray2.put(node);
}
}
}
if (jsonArray2.length() != 0) {
outData.put(jsonNameMuiti, jsonArray2);
}
return outData;
}
//需要生成的json格式如下
{
"test_report_1":[
{"test_2":"222222","test_6":"666666","test_5":"555555","test_4":"444444","test_1":"111111","test_3":"333333"}],
"test_report_2":[
{"reportDate2_4":"444444","reportDate2_6":"666666","reportDate2_5":"555555","reportDate2_3":"333333","reportDate2_2":"222222","reportDate2_1":"111111"}],
"test_result":[
{"case_name":"测试案例1","case_end_time":"2015-07-03 15-15-25","case_start_time":"2015-07-03 15-15-15","case_index":"0"},
{"case_name":"测试案例2","case_end_time":"2015-07-03 15-15-25","case_start_time":"2015-07-03 15-15-15","case_index":"1"},
{"case_name":"测试案例3","case_end_time":"2015-07-03 15-15-25","case_start_time":"2015-07-03 15-15-15","case_index":"0"},
{"case_name":"测试案例4","case_end_time":"2015-07-03 15-15-25","case_start_time":"2015-07-03 15-15-15","case_index":"0"}
]
}