下载引入包gson-2.0.jar
1.字符转数据
final Map map = new HashMap();
map.put("contents",
"[{\"Id\":\"111\",\"AcceptNum\":222,\"ArchiveNum\":333,\"ArchivRate\":444,\"CUR_DATA_DT\":555},{\"Id\":\"112\",\"AcceptNum\":222,\"ArchiveNum\":333,\"ArchivRate\":444,\"CUR_DATA_DT\":555}]");
map.put("footer", "{\"Id\":\"总合计\",\"AcceptNum\":151886,\"ArchiveNum\":449135}");
map.put("fields", "Id,AcceptNum,ArchiveNum,ArchivRate,CUR_DATA_DT"); String[] fields = {};// excel字段
String tempContent="";
JsonArray listArray = new JsonArray();
JsonObject object = new JsonObject();
JsonObject obj = new JsonObject();
obj = listArray.get(1).getAsJsonObject();
listArray = new JsonParser().parse(map.get("contents").toString()).getAsJsonArray();//json数组
if (map.containsKey("footer") && !map.get("footer").toString().trim().equals("")) {
footerJson = new JsonParser().parse(map.get("footer").toString()).getAsJsonObject();//json对象
map.remove("footer");
}
fields=map.get("fields").toString().trim().split(",", -1);//普通数组
tempContent= obj.get("Id").toString().replace("\"", "");//json存取
2.构造json对象
JsonObject object = new JsonObject();
// add the key/value property
object.addProperty("code", "0");
object.addProperty("msg", "error");
JsonArray listArray = new JsonArray();
JsonObject Row = new JsonObject(); for(int rownum=1;rownum<5;rownum++){
for (int colnum = 1; colnum <= 2; colnum++) { // insert the cell(columnName/columnValue) into the row
Row.addProperty("col"+colnum, "val"+colnum);
}
// insert one row into listTable "List"
listArray.add(Row);
}
JsonObject subObject = new JsonObject();
subObject.add("List", listArray);
subObject.addProperty("page", "1");
subObject.addProperty("page_size", "10");
subObject.addProperty("total_count", "25");
subObject.addProperty("page_count", "25");
object.add("result", subObject);
System.out.println(object.toString());
{"code":"0","msg":"error","result":{"page":"1","page_size":"10","total_count":"25","page_count":"25","List":[{"col1":"val1","col2":"val2"},{"col1":"val1","col2":"val2"},{"col1":"val1","col2":"val2"},{"col1":"val1","col2":"val2"},{"col1":"val1","col2":"val2"}]}}