Reputation: 203
I am trying to parse {"type_history":[["15","0.07","apple"],["13","0.03","banana"],["10","0.23","lemon"]]}
,I try to get array in JsonArray but fail.
String myJson="{"type_history":[["15","0.07","apple"],["13","0.03","banana"],["10","0.23","lemon"]]}";
ArrayList<UserType> rtn = new ArrayList<>();
JSONArray j=myJson.optJSONArray("type_history");
for (int i = 0; i < j.length(); i++) {
UserType tmp = new UserType();
JSONArray tmpArray = new JSONArray(Arrays.asList(j.get(i)));
tmp.setType(tmpArray.getString(0));
tmp.setValue(Float.parseFloat(tmpArray.getString(1)));
rtn.add(tmp);
}
in tmpArray.getString(0)
, I still get ["15","0.07","apple"]
,not get "15"
how to fix my code for get value from this array?
Upvotes: 0
Views: 327
Reputation: 1664
Here we go:
var listStr: JSONArray? = null
val json = "{type_history:[[15,0.07,apple],[13,0.03,banana],[10,0.23,lemon]]}"
val jsonObject = JSONObject(json)
val jsonArray = jsonObject.getJSONArray("type_history")
for(i in 0 until jsonArray.length()){
listStr = jsonArray.get(i) as JSONArray
for(x in 0 until listStr.length()) {
Log.d("mlogs", listStr.get(x).toString())
}
}
Upvotes: 0
Reputation: 3046
You have a JSONArray of JSONArrays.... so, lets say you want to get 15... you would do something like...
JSONObject o2 = new JSONObject(myJson);
JSONArray arr = o2.getJSONArray("type_history");
System.out.println(arr.getJSONArray(0).get(0));
Lets say you want to get all of the first elements in each.. you would do...
for (int i = 0; i < arr.length(); i++) {
System.out.println(arr.getJSONArray(i).get(0));
}
Let's dig more....
If you want to print everything...
for (int i = 0; i < arr.length(); i++) {
for (int j = 0; j < arr.getJSONArray(i).length(); j++) {
System.out.println(arr.getJSONArray(i).get(j));
}
System.out.println("----------");
}
That will print:
15
0.07
apple
----------
13
0.03
banana
----------
10
0.23
lemon
----------
I think your data structure should change tho. Its not very informative of what everything is. What does the 15, .07 mean from the apple? Maybe do a JSONArray of JSONObjects... would be a lot cleaner and easier to parse
You want to do whatever it takes to get away from hard coding indexes... (getJSONArray(0))
Upvotes: 1