7

I need to parse JSON array from Retrofit. I need to get the following key:

{
  "rc":0,
  "message":"success",
  "he":[
    {
      "name":"\u05de\u05e4\u05e7\u05d7",
      "type":0
    }
  ]
}

I can easily get the message but I am not able to get "he" array from response.

Here is my data model class

public class GetRoleData implements Serializable {

    @SerializedName("he")

    private ArrayList<Roles> he;

    @SerializedName("message")
    private String message;

    public GetRoleData() {
        this.he = new ArrayList<>();
        this.message = "";
    }

    public ArrayList<Roles> getUserRoles() {
        return he;
    }

    public String getMessage() {
        return message;
    }

    public class Roles {

        public Roles() {
            name = "";
            type = -1;
        }

        @SerializedName("name")

        private String name;
        @SerializedName("type")

        private int type;

        public int getType() {
            return type;
        }

        public String getName() {
            return name;
        }

    }
}

This is how I am sending request to the server:

@POST("index.php/")
Call<GetRoleData> getUserRoles(@Body SetParams body);

here is how i am sending request and handling response

APIService apiService = retrofit.create(APIService.class);

        Call<GetRoleData > apiCall = apiService.getUserRoles(params);
        apiCall.enqueue(new Callback<GetRoleData >() {


            @Override
            public void onResponse(retrofit.Response<GetRoleData > mUserProfileData, Retrofit retrofit) {

                Log.e("locale info", "mUserProfileData = " + mUserProfileData.body().toString());
                if (pDialog != null) {
                    pDialog.dismiss();
                }
                if (mUserProfileData.body().getMessage().equals("success")) {

                    Log.e("locale info", "user roles = " + mUserProfileData.body().getUserRoles().size());

                } else {
                    Toast.makeText(RegisterActivity.this, getResources().getString(R.string.get_role_error), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Throwable t) {

                if (pDialog != null) {
                    pDialog.dismiss();
                }

                t.printStackTrace();
            }
        });

What i want

I need to get the "he" array from above response. Please help Thanks.

here is response that i am getting..

enter image description here

6
  • Please paste the code where you are making the request and handling the response Commented Dec 17, 2015 at 6:39
  • @vipinagrahari please check. Commented Dec 17, 2015 at 6:48
  • what I am not able to get "he" array from response exactly means? Commented Dec 17, 2015 at 7:34
  • did you check the response whihc i need to parse? i need to get jsonArray from response which is "he" @Yazan Commented Dec 17, 2015 at 7:40
  • @Yazan please check updated question. i want to get the data in "he" Commented Dec 17, 2015 at 7:57

5 Answers 5

8

UPDATE FOR Retrofit 2.0-beta2:

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.google.code.gson:gson:2.4'
    compile 'com.squareup.okhttp:okhttp:2.5.0'
    // compile 'com.squareup.retrofit:retrofit:1.9.0'
    compile 'com.squareup.retrofit:retrofit:2.0.0-beta2'
    compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'
}

Interface:

@GET("/api/values")
Call<GetRoleData> getUserRoles();

MainActivity's onCreate:

        // Retrofit 2.0-beta2
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(API_URL_BASE)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        WebAPIService service = retrofit.create(WebAPIService.class);

        // Asynchronous Call in Retrofit 2.0-beta2
        Call<GetRoleData> call = service.getUserRoles();
        call.enqueue(new Callback<GetRoleData>() {
            @Override
            public void onResponse(Response<GetRoleData> response, Retrofit retrofit) {
                ArrayList<GetRoleData.Roles> arrayList = response.body().getUserRoles();
                if (arrayList != null) {
                    Log.i(LOG_TAG, arrayList.get(0).getName());
                }
            }

            @Override
            public void onFailure(Throwable t) {
                Log.e(LOG_TAG, t.toString());
            }
        });

Retrofit 1.9

I use your GetRoleData class

The interface:

public interface WebAPIService {        

    @GET("/api/values")
    void getUserRoles(Callback<GetRoleData> callback);                       
}

MainActivity:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);            

        // creating a RestAdapter using the custom client
        RestAdapter restAdapter = new RestAdapter.Builder()
                .setEndpoint(API_URL_BASE)
                .setLogLevel(RestAdapter.LogLevel.FULL)
                .setClient(new OkClient(mOkHttpClient))
                .build();

        WebAPIService webAPIService = restAdapter.create(WebAPIService.class);

        Callback<GetRoleData> callback = new Callback<GetRoleData>() {
            @Override
            public void success(GetRoleData getRoleData, Response response) {
                String bodyString = new String(((TypedByteArray) response.getBody()).getBytes());
                Log.i(LOG_TAG, bodyString);
            }

            @Override
            public void failure(RetrofitError error) {
                String errorString = error.toString();
                Log.e(LOG_TAG, errorString);
            }
        };

        webAPIService.getUserRoles(callback);
    }

The screenshot as the following:

enter image description here

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

11 Comments

what is RestAdapter i can't find in retrofit.
I use Retrofit 1.9, not 2.0 beta, compile 'com.squareup.retrofit:retrofit:1.9.0'
Ver 2.0, please note that RestAdapter is now also renamed to Retrofit. stackoverflow.com/questions/32424184/…
after switching back to 1.9.0. still Resadapter is unable to resolve
Thanks.. i got the error... actually i was doing exactly what i need to to do... Client didn't provide the complete information for api.. sometimes i get "he" as a JSONArray and some "en" as JSONArray. now i hit Url Using postman then i realize the error. Thanks. you are there when i need help. Thanks once again.
|
3

Mocky for tests -> http://www.mocky.io/v2/567275072500008d0e995b2c I'm using Retrofit 2 (beta-2). This works for me, nothing special about it:

Call definition:

@GET("/v2/567275072500008d0e995b2c")
Call<Base> getMock();

Models:

public class Base {
    public int rc;
    public String message;
    public List<Role> he;
}

public class Role {
    public String name;
    public int type;
}

Retrofit:

Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

Call execute:

webservice.getMock().enqueue(new Callback<Base>() {
    @Override
    public void onResponse(Response<Base> response, Retrofit retrofit) {

    }

    @Override
    public void onFailure(Throwable t) {

    }
});

9 Comments

it didn't work for me.. though it the code as i am doing
Test your code on my mocky link, change models to my version etc. There's gotta be a small bug somewhere.
hmmm okay let me try.
i am getting response from your mocky.. then whats wrong in my case?
So there's gotta be something wrong with the server response. Add HttpLoggingInterceptor to your client (tutorial) and check in logcat what exactly are you recieving. Maybe something wrong with encoding or you're not getting "he" jsonArray but "he" jsonObject. Hard to tell.
|
2

You have written all your getters except he correctly. In order for Retrofit to parse your JSON file, you should write your getter for he variable as follows.

public ArrayList<Roles> getHe() {
    return he;
}

Also, try removing new ArrayList from the constructor.

public GetRoleData() {
    // this.he = new ArrayList<>(); // <-- Remove here
    this.message = "";
}

11 Comments

can you write it please?
I have written it in my answer. You have written all your getters in the correct format except he variable. You need to write it as getHe (instead of getUserRoles) in order for Retrofit to parse JSON format.
still no success after changing getRoles to getHe().
Are you getting the data except he, or do you fail at receiving response.body() ?
Please try removing arraylist initialization from the constructor. See my updated answer @MustanserIqbal
|
1

// Use the following Pojo Classes

public class GetRoleData {

@SerializedName("rc")
@Expose
private Integer rc;
@SerializedName("message")
@Expose
private String message;
@SerializedName("he")
@Expose
private List<He> he = new ArrayList<He>();

/**
*
* @return
* The rc
*/
public Integer getRc() {
return rc;
}

/**
*
* @param rc
* The rc
*/
public void setRc(Integer rc) {
this.rc = rc;
}

/**
*
* @return
* The message
*/
public String getMessage() {
return message;
}

/**
*
* @param message
* The message
*/
public void setMessage(String message) {
this.message = message;
}

/**
*
* @return
* The he
*/
public List<He> getHe() {
return he;
}

/**
*
* @param he
* The he
*/
public void setHe(List<He> he) {
this.he = he;
}

}
-----------------------------------com.example.He.java-----------------------------------

package com.example;

import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;


public class He {

@SerializedName("name")
@Expose
private String name;
@SerializedName("type")
@Expose
private Integer type;

/**
*
* @return
* The name
*/
public String getName() {
return name;
}

/**
*
* @param name
* The name
*/
public void setName(String name) {
this.name = name;
}

/**
*
* @return
* The type
*/
public Integer getType() {
return type;
}

/**
*
* @param type
* The type
*/
public void setType(Integer type) {
this.type = type;
}

}

8 Comments

No success... it is same as my my code.. whats the difference in your code
What Response are you getting in Logs
i am getting message as success but no data for he
Did you add converter to retrofit Builder? .addConverterFactory(GsonConverterFactory.create());
yes i did this retrofit = new Retrofit.Builder() .baseUrl(URL) .addConverterFactory(GsonConverterFactory.create()) .build();
|
0

Another easy way of getting data using webservices is by using JsonElement and then convert it into JsonObject and parse JsonObject. Ez-Pz.

Note : JsonObject is not same as JSONobject, JsonObject belongs to GSON's library

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.