利用for構造json
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); } }
輸出結果:google
[{"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"}]
遍歷:spa
//遍歷 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); } }