java 构造json对象数组

利用for构造

import com.google.gson.JsonArray;
import com.google.gson.JsonObject; public class Test {
public static void main(String[] args) {
final JsonArray listArray = new JsonArray();
final JsonObject object = new JsonObject();
for (int i = 0; i < 5; i++) {
final JsonObject obj = new JsonObject();
for (int n = 0; n < 3; n++) {
obj.addProperty("col" + n, "val" + i + n);
}
listArray.add(obj);
} System.out.println(listArray); }
}

输出结果:

[{"col0":"val00","col1":"val01","col2":"val02"},
{"col0":"val10","col1":"val11","col2":"val12"},
{"col0":"val20","col1":"val21","col2":"val22"},
{"col0":"val30","col1":"val31","col2":"val32"},
{"col0":"val40","col1":"val41","col2":"val42"}]

遍历:

//遍历
String key, value;
String jsonString="[{\"Id\":\"111\",\"AcceptNum\":222,\"ArchiveNum\":333,\"ArchivRate\":444,\"CUR_DATA_DT\":555},{\"Id\":\"112\",\"AcceptNum\":222,\"ArchiveNum\":333,\"ArchivRate\":444,\"CUR_DATA_DT\":555}]";
JsonArray listArray=new JsonParser().parse(jsonString).getAsJsonArray();
for (int i = 0; i < listArray.size(); i++) {
JsonObject obj = new JsonObject();
obj = listArray.get(i).getAsJsonObject();
//jsonString="{\"Id\":\"111\",\"AcceptNum\":222,\"ArchiveNum\":333,\"ArchivRate\":444,\"CUR_DATA_DT\":555}";
//obj=new JsonParser().parse(jsonString).getAsJsonObject();
//vlaue=obj.get("AcceptNum").toString().replace("\"", "");
final Iterator iterator = obj.entrySet().iterator();
while (iterator.hasNext()) {
final Map.Entry entry = (Map.Entry) iterator.next();
key = (String) entry.getKey();
value = obj.get(key).toString().replace("\"", "");
System.out.println(key + "====" + value);
}
}
上一篇:HTTP 常见的状态码


下一篇:MySQL——修改数据库远程权限