Skip to content Skip to sidebar Skip to footer

Handling A Json Response

I have Asp.net Api to get JSON response like this: {\'UserID\':5,\'UserName\':\'asd\',\'Password\':\'asd\',\'Email\':\'ss@asd\',\'PhoneNumber\':\'1213\',\'Logtit\':0.0,\'Latitle\':

Solution 1:

Most probably you are getting a string respone. If its a string then firstly conver it to Json Object.. you can do this as following below.

JSONObject jsonObject=newJSONObject(response);

If it is JSONObject already then try to conver it to java object as following:

int userId=jsonObject.getInt("UserID");
String userName=jsonObject.getString("UserName");
String pass=jsonObject.getString("Password");

Put the code in your onResponse. and lastly seems like you are getting an array of object. Then create a POJO class like below:

publicclassUserData {
    @Expose@SerializedName("UserId")
    private int userId;
    @Expose@SerializedName("UserName")
    privateString userName;
    .
    .
    .
   //add the extra attribute and create getter and setterpublic int getUserId() {
        return userId;
    }

    publicvoidsetUserId(int userId) {
        this.userId = userId;
    }

    publicStringgetUserName() {
        return userName;
    }

    publicvoidsetUserName(String userName) {
        this.userName = userName;
    }
} 

Then in declare in your code:

ArrayList<UserData>userDataList=newArrayList();

Follow the below method to set data to arraylist with json data parsing

int userId=jsonObject.getInt("UserID");
String userName=jsonObject.getString("UserName");
String pass=jsonObject.getString("Password");    
UserData userInfo=new UserData();
userInfo.setUserId(userId)
userIfo.setUserName(userName);
//add the other attribute similiarly
userDataList.add(userInfo);

Solution 2:

You could parse it into a Map using GSON. Please refer to this question and answer for more information.

Post a Comment for "Handling A Json Response"