java - 将 json 对象添加到 jsonarray android/Java

标签 java android arrays

我得到一个具有以下值的 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/

相关文章:

java - 使用 asm Instrumentation 测量 java 程序运行时间

android - Cordova 地理定位插件无法从适用于 Android 的 GPS 获取位置

android - 为什么列表首选项中的条目没有显示在应用程序中?

java - 我的项目中缺少什么注释?

java - 一个 for 循环中的两个 for 循环的运行时间复杂度

安卓源?

android - GCM 使用两个不同的工作注册 ID 进行注册

c# - 尝试对没有所有元素的数组列表进行排序

javascript - toFixed 正在字符串中转换。我们怎样才能换算成数字呢?

java - 如何在 Spring 运行时从文本文件重新加载数据