[英]Retrieving result from JSON to ArrayList
I have the following JSON- 我有以下JSON-
{obj} 0
{obj} 1
{obj} 2
My plan is to iterate through values "journeys" and store them in an ArrayList
. 我的计划是遍历值“旅程”并将它们存储在
ArrayList
。 Similarly, store "legs" in another ArrayList
and finally get retrieve the value for the object instruction
. 同样,将“腿”存储在另一个
ArrayList
,最后获取检索对象instruction
的值。 As you can see parent journeys
has 3 child {obj} 0
, {obj} 1
, {obj} 2
. 如您所见,父
journeys
有3个孩子{obj} 0
, {obj} 1
, {obj} 2
。 I can get the journeys
stored using -- 我可以使用以下方式存储
journeys
:
ArrayList<JSONObject> journey = new ArrayList<>();
ArrayList<JSONArray> leg = new ArrayList<>();
ArrayList<JSONObject> legDetails = new ArrayList<>();
try {
JSONArray jArray = object.getJSONArray("journeys");
if (jArray != null) {
for (int i=0;i<jArray.length();i++){
journey.add(jArray.getJSONObject(i));
}
if (!journey.isEmpty()){
for (int j=0;j<journey.size();j++){
leg.add(journey.get(j).getJSONArray("legs"));
}
}
if (!leg.isEmpty()){
for (int i = 0; i<leg.size();i++){
legDetails.add(leg.get(i).getJSONObject(i));
}
}
}
}
catch (JSONException e) {
e.printStackTrace();
}
Now each journey returns 2 legs and the number changes time to time. 现在,每次旅程都会返回2条腿,并且数字会不时变化。 I was expecting 6
JSONObject
at the end of last for
loop but I only get 2 and a out of range exception. 我在last
for
循环的末尾期望6 JSONObject
,但是我只得到2和一个超出范围的异常。
Things to remember: Journey has Routes (Obj 0,1,2). 要记住的事情:旅途有路线(Obj 0,1,2)。 Routes has legs (Obj 0,1).
路线有支腿(Obj 0,1)。 Legs consists of
instruction
with detail
string. 腿由带
detail
字符串的instruction
组成。
Is this right approach to retrieve the value? 这是获取价值的正确方法吗? and what am I doing wrong?
我在做什么错?
problem is here 问题在这里
if (!journey.isEmpty()){
for (int j=0;j<journey.size();j++){
leg.add(journey.get(j).getJSONArray("legs"));
}
}
journery's have 3 objects. 旅程有3个对象。
for j=0 you add journey[0] array to leg
for j=1 you add journey[1] array to leg
for j=2 you add journey[2] array to leg
so legs will have 3 arrays. 所以腿将有3个阵列。
if (!leg.isEmpty()){
for (int i = 0; i<leg.size();i++){
legDetails.add(leg.get(i).getJSONObject(i));
}
}
here leg.size()=3; 在这里leg.size()= 3;
for i=0 it will add leg[0]'s [0]th element
for i=1 it will add leg[1]'s [1]th element
for i=2 it will add leg[2]'s [2]th element (this is out of range)
update :: 更新::
if (!leg.isEmpty()){
for (int i = 0; i<leg.size();i++){
for(int j=0;j<leg.get(i).size();j++)
legDetails.add(leg.get(i).getJSONObject(j));
}
}
This should help 这应该有帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.