简体   繁体   中英

do calculation inside JSONArray in Java

I have a simple issue but cannot solve it as I am not very good at algorithm! I have an JSONArray in this form:

[{"values":[{"time":1434976493,"value":"50"},
{"time":1434976494,"value":"100"}],"counter":"counter1"},

{"values":[{"time":1434976493,"value":"200"},
{"time":1434976494,"value":"300"}],"counter":"counter2"},

{"values":[{"time":1434976493,"value":"400"},   
{"time":1434976494,"value":"600"}],"counter":"total"}]

What I want to do is to get the integer value for counter 1 and counter 2 and then divide them by total counter and put them in a list or array. and of course I want total counter to be untouched! So the calculation would be Counter1.value/total.value , Counter2.value/total.value So for example the counter 1 would be like this:

{"values":[{"time":1434976493,"value":"50/400"},{"time":1434976494,"value":"100/600"}],"counter":"counter1"}

Thats an uncompleted attempt :

(given that I have list of counters that I can iterate:)

int index= counters.indexOf("total");
JSONObject rec = array.getJSONObject(index);

and then I got this for total counter:

{"values":[{"time":1434976493,"value":"400"},   
    {"time":1434976494,"value":"600"}]

not sure what is the next step?!

Here's what I would do. Replace <JSON STRING HERE> with the JSON String you were going to parse:

ArrayList<ArrayList<Integer>> resultList = new ArrayList<ArrayList<Integer>>();

JSONArray arr = new JSONArray(<JSON STRING HERE>);

for(int i = 0; i < arr.length(); i ++)
{
    JSONObject obj = arr.getJSONObject(i);
    JSONArray valueArray = obj.getJSONArray("values");

    ArrayList<Integer> dataList = new ArrayList<Integer>();
    resultList.add(dataList);

    for(int j = 0; j < valueArray.length(); j ++)
    {
        JSONObject valueObject = valueArray.getJSONObject(j);
        Integer value = valueObject.getInt("value");
        dataList.add(value);
    }
}

The result is a list of lists of Integers called resultList. Good luck!

Remember, you have to wrap the whole thing in a try,catch as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM