3

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?

6 Answers 6

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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
}

Comments

1

Simple Json Parsing would be like this

JSONObject params=new JSONObject(httpResult);
JSONObject params1=params.getJsonObject("Friends");
JsonArray array=params1.getJsonArray();

for(int i=0;i<array.length();i++)
{
String userName=array.getJsonObject(i).getString("UserName");
// Do whatever you want to do with username
}

Comments

1

Following code works good without any use of GSON , Please try .

String jsonString = "Your Json Data";
  JSONObject  jsonRootObject = new JSONObject(jsonString );  
JSONArray friendsArray = jsonRootObject .getJSONArray("Friends");

ArrayList<FriendList > friendsList = new ArrayList<FriendList >();


for(int friendsLen = 0 ;friendsLen  < friendsArray .length() ; friendsLen ++){
FriendList userNameObj = new UserName();
JSONObject jsonObj = jsonRootObject.getJSONObject(friendsLen )  ;
String Username = jsonObj.getString("Username"); 
userNameObj .setUserName(Username ); 
friendsList .add(userNameObj );
}

Now friendsList the list which you want .

Comments

1

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

This cannot work because it expects your whole JSON document to be just an array of FriendList element (by the way, why "FriendList"?): [{"Username": "abc"},{"Username": "xyz"}] -- this is what can be parsed by your approach.

The easiest solution to fix this (apart from harder to implement but more efficient streamed reading in order to peel of possible unnecessary properties) is just creating a correct mapping:

final class Wrapper {

    @SerializedName("Friends")
    final List<Friend> friends = null;

}
final class Friend {

    @SerializedName("Username")
    final String username = null;

}

Now deserialization is trivial and you don't have to define a type token because Gson has enough information for the type from the Wrapper.friends field:

final Wrapper wrapper = gson.fromJson(response, Wrapper.class);
for ( final Friend friend : wrapper.friends ) {
    System.out.println(friend.username);
}

Output:

abc
xyz

Comments

0

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

to

 FriendList friends = new Gson().fromJson(httpResult, listType);
 List<Friend> friends = friends.list;

Updated FriendList.java as mentioned below

FriendList.java

public class FriendList
{
     @SerializedName("Friends")
     public List<Friend> list;
}

Friend.java

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

     public String getUsername() 
     {
         return username;
     }

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.