Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android: Retrieve values from nested JSON object into List type

I have a nested JSON array from which I need to retrieve values of all Usernames nested within Friends.

{
    "Friends": [
        {"Username": "abc"},
        {"Username": "xyz"}
    ]
}

After I get all the usernames, I want to store it in a List that I will use with an adapter and ListView.

FriendList.java:

public class FriendList
{
     @SerializedName("Username")
     private String username;

     public String getUsername() 
     {
         return username;
     }

     public void setUsername(String username) 
     {
         this.username = username;
     }
}

This is the code that I have written so far:

if (httpResult != null && !httpResult.isEmpty()) //POST API CALL
{
   Type listType = new TypeToken<List<FriendList>>() {}.getType();

   List<FriendList> friendList = new Gson().fromJson(httpResult, listType);

   FLCustomAdapter adapter = new FLCustomAdapter(getActivity(), friendList);

   mainFriendsListView.setAdapter(adapter);
}

However, an error occurs: Failed to deserialize Json object.

Please suggest, what additions/changes should be made to it, so that I can retrieve nested JSON values into a list?

like image 892
Simran Avatar asked Mar 16 '26 08:03

Simran


2 Answers

First of all, You have to understand the strucure of this Json. You can see, it contains

1 . A json object

2 . This json object contains a json array which can include several different json objects or json arrays. In this case, it contains json objects.

Parsing:

Get the Json Object first

  try{
    JSONObject jsonObject=new JSONObject(jsonResponse);
    if(jsonObject!=null){
    //get the json array
    JSONArray jsonArray=jsonObject.getJSONArray("Friends");
    if(jsonArray!=null){
    ArrayList<FriendList> friendList=new ArrayList<FriendList>();
    //iterate your json array
    for(int i=0;i<jsonArray.length();i++){
    JSONObject object=jsonArray.getJSONObject(i);
    FriendList friend=new FriendList();
    friend.setUserName(object.getString(Username));
    friendList.add(friend);
    }
    }
    }
    }
    catch(JSONException ex){
    ex.printStackTrace();
    }

hope, it will help you.

like image 63
Mansuu.... Avatar answered Mar 18 '26 20:03

Mansuu....


Solution with GSON.

You need to two class to parse this.

FriendList and UsernameDao.

public class UsernameDao {
  @SerializedName("Username")
  private String username;

  //get set methods
}
like image 27
Vorathep Sumetphong Avatar answered Mar 18 '26 22:03

Vorathep Sumetphong



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!