Reputation: 220
I have JSONArray with different JSONObjects in it. When my method will be called at that time first JSONObject will be created. When again that method will be called then another JSONObject will be called beside the previous JSONObject. Now i want the element from the latest JSONObject inserted. And the problem is that JSONObject is inserted anywhere in JSONArray. So how can i get the element of latest JSONObject inserted. Here is my JSONArray
[
{
"letter": "E",
"col": 2,
"row": 5,
"badge": "1"
},
{
"letter": "D",
"col": 2,
"row": 6,
"badge": "2"
},
{
"letter": "Y",
"col": 2,
"row": 8,
"badge": "3"
}
]
In above JSONArray i want the letter from the latest JSONObject created in android. I have done following things in my code but i am not getting proper letter as JSONObject is placed anywhere.
JSONArray jarry1 = new JSONArray(allwordsss);
for (int i = 0; i < jarry1.length(); i++) {
String all = jarry1.getString(i).toString();
Log.e("TAG2", "All" + all);
JSONObject jobjjjj = new JSONObject(all);
letter = jobjjjj.getString("letter");
}
Log.i("TAG2", "letter" + letter);
Upvotes: 1
Views: 2686
Reputation: 1241
Try this it will help you.
try{
JSONArray jarry1 = new JSONArray(allwordsss);
JSONObject jobject
for(int i=0; i<jarry1.size(); i++)
{
jobject = jarry1.getJSONObject(i)
String letter = jobject.get("letter")
Log.i("TAG", "letter" + letter);
}
catch(JSONException e){
}
Upvotes: 3
Reputation: 5905
Try following code, You can get whether specific json object is available in response json or not. If yes then get it.
try{
JSONArray results = jsonObject.getJSONArray(allwordsss);
for (int i = 0; i < results.length(); i++) {
JSONObject jsonResult = results.getJSONObject(i);
// To check whether such key available or not, otherwise will through exception
if (jsonResult.has("letter"))
String letter = jsonResult .getString("letter");
}
}catch(JSONException e){
}
Upvotes: 1
Reputation: 1917
to access to the latest letter in your array:
String letter;
try {
JSONArray array = new JSONArray(json);
JSONObject object = array.getJSONObject(array.length()-1);
if (object.has("letter")) // according to defensive programming rules
letter = object.getString("letter");
catch {
letter = "error...";
}
Upvotes: 1