How to parse JSON arrays with retrofit - java

I have JSON file like this http://androiddocs.ru/api/friends.json
{
"data":"dbfriends",
"friends": [{"id":"1","name":"Andrew","city":"Moscow","contacts":{"mobile":"+7 0000000","email":"andrew#androiddocs.ru","skype":"andrew"}}, {"id":"2","name":"Ivan","city":"Kiev","contacts":{"mobile":"+38 0000000","email":"ivan#androiddocs.ru","skype":"ivan"}}]
}
my retrofit interface
public interface Friends_API {
String BASE_URL = " http://androiddocs.ru/api/";
#GET("friends.json") Call<Friends> getFriends();
class Factory {
private static Friends_API service;
public static Friends_API getInstance(){
if (service == null) {
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(BASE_URL)
.build();
service = retrofit.create(Friends_API.class);
return service;
} else {
return service;
}
}
}
}
POJO file generated by http://www.jsonschema2pojo.org/
and my code to get data value and:
Friends_API.Factory.getInstance().getFriends().enqueue(new Callback<Friends>() {
#Override
public void onResponse(Call<Friends> call, Response<Friends> response) {
String getData = response.body().getData();
}
#Override
public void onFailure(Call<Friends> call, Throwable t) {
}
}
i can't understood how i can get value: id, name, city...
thanks for help!

You can get the data from retrieved response using:
Friends friends = response.body();
And then you can retrieve the List<Friend> using friends.getFriends() object. Now you can iterate through this list of friends and can get id,name, city or contact details.

Related

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 39 path $.message

i am making login function in android using retrofit. I have created an endpoint for login validation, then I have tested it using Postman using raw (json) and it worked. But when I enter the endpoint into android using retrofit I get an error message like this:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 39 path $.message
can anyone help me?
So here my source:
ApiClient
public class ApiClient {
public static final String BASE_URL = "";
public static Retrofit retrofit;
public static Retrofit getRetrofit() {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(ScalarsConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
AuthInterface
public interface AuthInterface {
#Headers("Content-Type: application/json")
#POST("auth/login")
Call<AuthPost> authPostCall(#Body String body);
}
AuthPost
public class AuthPost {
#SerializedName("status")
private String status;
#SerializedName("error_code")
private int error_code;
#SerializedName("message")
private String message;
#SerializedName("token")
private String token;
...getter and setter
}
LoginActivity
JSONObject payload = new JSONObject();
try {
payload.put("login_username", loginUsernameText);
payload.put("login_password", loginPasswordText);
} catch (JSONException e) {
e.printStackTrace();
}
Call<AuthPost> authPostCall = authInterface.authPostCall(payload.toString());
authPostCall.enqueue(new Callback<AuthPost>() {
#Override
public void onResponse(Call<AuthPost> call, Response<AuthPost> response) {
if (response.code() == 200) {
} else {
}
}
#Override
public void onFailure(Call<AuthPost> call, Throwable t) {
t.printStackTrace();
}
});
Are you sure about:
#SerializedName("message")
private String message;
Usually this error appears if this field is Object.
Does your JSON looks like
"message":"test"
or something like:
"message":{"field":"value"}
If it is the second variant so you should simple change the field to necessary type.

Android Retrofit 2 - problem with sending the Array<Object> using POST

im new with retrofit and now, when i know how to sent the normal data without any objects, just with parameters or simple body i want to know how to sent the objects...
I spent like 20h to debug it and i'm confused because i dont know how to do this...
There is my codes:
API Interface:
#POST("/api/assortment")
Call<PostAssortment> getAssortment(#Body String PostShipmentProgress);
PostAssortment class:
public class PostAssortment {
private String JSON;
#SerializedName("token")
#Expose
private String token;
#SerializedName("assortment")
#Expose
private Assortment assortment;
#SerializedName("tokens")
#Expose
private List<String> tokens;
#SerializedName("positions")
#Expose
private List<Position> positions;
#SerializedName("deviceId")
#Expose
private String deviceId;
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public Shipment getAssortment() {
return assortment;
}
public void setAssortment(Assortment assortment) {
this.assortment = assortment;
}
public List<String> getTokens() {
return tokens;
}
public void setTokens(List<String> tokens) {
this.tokens = tokens;
}
public List<Position> getPositions() {
return positions;
}
public void setPositions(List<Position> positions) {
this.positions = positions;
}
public String getDeviceId() {
return deviceId;
}
public void setDeviceId(String deviceId) {
this.deviceId = deviceId;
}
public String getJSON() {
return JSON;
}
public void setJSON(String JSON) {
this.JSON = JSON;
}
}
And the mainJava class:
Gson gson = new Gson();
PostAssortment postAssortment= new PostAssortment();
List<String> tokens = new ArrayList<>();
tokens.add("someToken");
postAssortment.setTokens(tokens);
postAssortment.setDeviceId("aaaaa");
List<Position> currentPosition = new ArrayList<>();
Position cp = new Position();
cp.setItemName("Some");
cp.setPlace("POLAND");
cp.setTimestamp("2020-12-09T11:00:00");
currentPosition.add(cp);
postAssortment.setPositions(currentPosition);
String postAssortmentJSON = gson.toJson(postAssortment);
Call<PostAssortment> call = ApiLoginInterface.getAssortment(postAssortmentJSON);
call.enqueue(new Callback<PostAssortment>() {
#Override
public void onResponse(Call<PostAssortment> call, Response<PostAssortment> response) {
PostAssortment assortmentResponse = response.body();
}
#Override
public void onFailure(Call<PostAssortment> call, Throwable t) {
Log.d("FAILURE", "onFailure: " + t.getMessage());
}
});
}
And my retrofit onCreate:
Gson gson = new GsonBuilder()
.setLenient()
.create();
String BASE_URL = getString(API_URL);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
ApiLoginInterface = retrofit.create(ApiLoginInterface.class);
And after im trying to call it im not getting any point on call enqueue just a
Android: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
Error...
Can someone describe this and help me to make it work? :/
You haven't provided enough information to help identify the error. Probably add the full stacktrace to the question as well. But if your API post request is expecting a json body I would start with the fixes below:
Remove this:
String postAssortmentJSON = gson.toJson(postAssortment);
Then pass your object as a pojo to your retrofit interface like this:
#POST("/api/assortment")
Call<PostAssortment> getAssortment(#Body PostAssortment postAssortment);
Then when doing your call you don't need to convert it to a string json string. The adapter does that for you:
Call<PostAssortment> call = ApiLoginInterface.getAssortment(postAssortment);
Post assortment in my problem will be in a list, so to make it works I need to change the Call to

Fetch data from server using retrofit method

i want fetch data from server, i have API URL like example : https://example.com/PlanController/getData/2/7k Plan, int his api url 2 is dynamic value and 7k plan is also dynamic Value. i want fetch data from retrofit method. give me some examples.
public interface APIService {
#GET("PlanController/getData")
Call<CoachListResponse> getAllData();
}
Retrofit clint
public class RetrofitClient {
private static Retrofit retrofit = null;
public static Retrofit getClient(String baseUrl) {
Gson gson = new GsonBuilder().setLenient().create();
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
}
return retrofit;
}
}
Define service after creating the retrofit
public interface APIService {
#GET("getData/{id}/{kid}")
Call<CoachListResponse> getAllData(#Path("id") Long id, #Path("kid") String kid);
}
public class RetrofitClient {
private static APIService service;
public static Retrofit getClient(String baseUrl) {
Gson gson = new GsonBuilder().setLenient().create();
if (retrofit == null) {
retrofit = new Retrofit.Builder().baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create(gson)).build();
}
service = retrofit.create(APIService.class);
return retrofit;
}
public static void getAllData(Callback<CoachListResponse> callback) {
Call<CoachListResponse> regionsCall = service.getAllData();
regionsCall.enqueue(callback);
}
}
, consume
RetrofitClient.getClient("https://example.com/PlanController/").getAllData(new Callback<CoachListResponse>() {
#Override
public void onResponse(Call<CoachListResponse> call, Response<CoachListResponse> response) {
CoachListResponse responseDto = response.body();
// logic
}
#Override
public void onFailure(Call<CoachListResponse> call, Throwable t) {
// logic
}
}, );
I wanted to replace only a part of the URL, and with this solution, I don't have to pass the whole URL, just the dynamic part and Your Retrofit client as it is no need to change:
public interface APIService {
#GET("PlanController/getData/{value}/{plan}")
Call<CoachListResponse> getAllData(#Path(value = "value", encoded = true) String value, #Path(value = "plan", encoded = true) String plan);
}

to call the retrofit in different classes

I am a beginner to the android. I am using Retrofit to call the API. But I would like to write the retrofit call method only once and use the same function in different API calls in my application. I try to create It's a generic method in nonactivity class and use it in my activity class.
public static generic_Retrofit_Class apiClient;
private Retrofit retrofit = null;
public static generic_Retrofit_Class getInstance() {
if (apiClient == null) {
apiClient = new generic_Retrofit_Class();
}
return apiClient;
}
public Retrofit getclient()
{
return getclient(null);
}
private Retrofit getclient(Object o) {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.level(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder okHttpClient = new OkHttpClient.Builder();
okHttpClient.readTimeout(60, TimeUnit.SECONDS);
okHttpClient.writeTimeout(60, TimeUnit.SECONDS);
okHttpClient.connectTimeout(60, TimeUnit.SECONDS);
okHttpClient.addInterceptor(interceptor);
okHttpClient.addInterceptor(new Interceptor() {
#Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request request = chain.request();
return chain.proceed(request);
}
});
retrofit = new Retrofit.Builder()
.baseUrl(Constant.Baseurl)
.client(okHttpClient.build())
.addConverterFactory(GsonConverterFactory.create())
.build();
return retrofit;
}
After this code when I call this method in my Activity class it shows an error. Here is the implementation of the method in the Activity class.
private void Getstock() {
final String mid = medicineid.getText().toString().trim();
final String batch = batchno.getText().toString().trim();
if (medicineid.getText().length() != 0 && batchno.getText().length() != 0) {
App_Interfaces app_interfaces = (App_Interfaces) new generic_Retrofit_Class().getclient().create(App_Interfaces.class);
Map<String, String> mapdata = new HashMap<>();
mapdata.put("mid", mid);
mapdata.put("batch", batch);
final Call<Response> getstock_call = app_interfaces.getstock(mapdata);
getstock_call.enqueue(new Callback<Response>() {
#Override
public void onResponse(Call<Response> call, Response<Response> response) {
if (response.isSuccessful() && response.body() != null && response != null) {
String jsonresponse = response.body().toString();
parseStockData(jsonresponse);
System.out.print(jsonresponse);
return;
}
}
#Override
public void onFailure(Call<Response> call, Throwable t) {
}
});
}
Here is the error
java.lang.IllegalArgumentException: 'retrofit2.Response' is not a valid response body type. Did you mean ResponseBody?
for method App_Interfaces.getstock
here is my Interface Code
public interface get_stock
{
#GET("/getstock")
Call<Response> getstock(#QueryMap Map<String, String> options);
}
Welcome to SO
Change the getClient method code as
public class YOUR_CLASS{
private static YOUR_API_INTERFACE retrofit = null;
public static YOUR_API_INTERFACE getClient() { // no need to pass the object params
if(retrofit == null){
//you client code same as you written in question
retrofit = new Retrofit.Builder()
.baseUrl(Constant.Baseurl)
.client(okHttpClient.build()) //okHtttpClient from your client code
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit.create(YOUR_API_INTERFACE.class);
}
}
Now, you can easily access the retrofit api interface by YOUR_CLASS.getClient(). This will return your Retrofit Interface
Your Retrofit Interface with declare method should be like this
public interface YOUR_API_INTERFACE {
#GET("your api name")
Call<YOUR_POJO> yourApi();
}
In your activity/fragment class you can access the yourApi method as
YOUR_CLASS.getClient().yourApi();

Make a GET and POST service call with Retrofit with the use of Protobuf (Protocol Buffer)

Can anyone please give me some example how we can use protobuf in retrofit - I tried but its failed with some error , let me give you a sample of my implementation on that.
I hope you guys will help me.
ApiInterface.java
public interface ApiInterface {
#GET
Call<CommonProto.Country> makeGetRequest(#Url String url);
}
ApiClient.java
public class ApiClient {
public static final String BASE_URL = "**************************";
private static Retrofit retrofit = null;
public static Retrofit getClient() {
if (retrofit==null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(Proto3ConverterFactory.create())
.build();
}
return retrofit;
}
}
MainActivity.java
ApiInterface apiService =
ApiClient.getClient().create(ApiInterface.class);
Call<CommonProto.Country> call = apiService.makeGetRequest("Services/CountryServices/GetAllCountry");
call.enqueue(new Callback<CommonProto.Country>() {
#Override
public void onResponse(Call<CommonProto.Country> call, Response<CommonProto.Country> response) {
String bodyString = null;
try {
Log.e("RETROFIT ::::::: ", String.valueOf(response.body())+"TEST");
} catch (Exception e) {
Log.e("RETROFIT ERROR ::::::: ", e.getMessage()+"TEST");
e.printStackTrace();
}
}
#Override
public void onFailure(Call<CommonProto.Country> call, Throwable t) {
// Log error here since request failed
Log.e(TAG, t.toString());
}
}
);
when i run this way i got the error
java.lang.RuntimeException: com.google.protobuf.InvalidProtocolBufferException: Protocol message tag had invalid wire type.
my Proto.java file and also have Proto.proto file both are here in this link,
https://drive.google.com/folderview?id=0B4loQuzINvHCRUlNbk5LUXE1NXM&usp=sharing
Please let me know how to do this GET Req and also I was Struggling with POST Req.
you can create interface like this
public interface LoginInterface {
#FormUrlEncoded
#POST("url goes here")
Call<LoginResponseData> getUserLoginDeatail(#FieldMap Map<String, String> fields);
}
make an instance of retro file and call interface method something like this
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("base url")
.build();
webApis = retrofit.create(WebApis.class);
Call<LoginResponseData> call = webApis.getCurrentRide(keyValue);
call.enqueue(new Callback<LoginResponseData>() {
#Override
public void onResponse(Call<LoginResponseData> call, Response<LoginResponseData> response) {
try {
} catch (Exception e) {
// customizedToast.showToast(context.getResources().getString(
// R.string.exception));
e.printStackTrace();
}
}
#Override
public void onFailure(Call<LoginResponseData> call, Throwable t) {
}
});
for protocol buffer you can find a reference here

Categories