我得到一个具有以下值的 JSONarray:
[{"id":"1","type":"7"},
{"id":"2","type":"6"},
{"id":"5","type":"5"},
{"id":"6","type":"4"}]
等等。
问题是,我想从这个数组中编写一个新数组,该数组有一个额外的字段,该字段是“id”与“type”的乘法。像这样的事情:
[{"id":"1","type":"7","result","7"},
{"id":"2","type":"6","result","12"}]
等等。
我怎样才能实现这个目标?
最佳答案
您可以使用 Google 的 GSON 包及其内部 JSON 实现,如下所示。
假设您已预先填充 jsonArray:
JsonArray values = what_ever_your_values_are; (if you define you data stream i can guide you further)
JsonArray newJsonArray = new JsonArray();
for(int i=0;i<values.size();i++){
JsonObject temp = new JsonObject();
temp.addProperty("id",values.get(i).getAsJsonObject().get("id").getAsString());
temp.addProperty("type",values.get(i).getAsJsonObject().get("type").getAsString());
int result = Integer.parseInt(values.get(i).getAsJsonObject().get("id").getAsInt()) *
Integer.parseInt(values.get(i).getAsJsonObject().get("type").getAsInt()); //for the sake of simplicity
temp.addProperty("result",String.valueOf(result));
newJsonArray.add(temp);
}
关于java - 将 json 对象添加到 jsonarray android/Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26050370/