简体   繁体   English

在 Java 中的 JSONArray 中进行计算

[英]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:我有一个这种形式的 JSONArray:

[{"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.我想要做的是获取计数器 1 和计数器 2 的整数值,然后将它们除以总计数器并将它们放入列表或数组中。 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:所以计算将是Counter1.value/total.valueCounter2.value/total.value所以例如计数器 1 将是这样的:

{"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:<JSON STRING HERE>替换为您要解析的 JSON 字符串:

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.结果是一个名为 resultList 的整数列表列表。 Good luck!祝你好运!

Remember, you have to wrap the whole thing in a try,catch as well.请记住,您必须将整个事情包装在 try 中,catch 也是如此。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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