2014-09-26 83 views
1

我得到一個JSONarray具有此值:添加JSON對象jsonarray的Android/Java的

[{"id":"1","type":"7"}, 
{"id":"2","type":"6"}, 
{"id":"5","type":"5"}, 
{"id":"6","type":"4"}] 

等。

問題是我想寫一個新的數組,這個數組有一個額外的字段,即「type」的「id」的乘法。類似這樣的:

[{"id":"1","type":"7","result","7"}, 
{"id":"2","type":"6","result","12"}] 

等等。

我該如何做到這一點?

回答

0

您可以使用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); 
} 
+0

我給了一槍,報到! – pihh 2014-09-28 00:28:22