How to get JSON object using Retrofit? - android

I'm trying to read this JSON using Retrofit but I got this error Could not locate ResponseBody converter for class org.json.JSONObject.
The JSON in ALE2 file
{
"a1":[...],
"a2":[...],
"a3":[...]
}
Code
Retrofit retrofit = new Retrofit.Builder().baseUrl(Constants.BASE_URL).build();
retrofit.create(RetrofitInterface.class).getData().enqueue(new Callback < JSONObject > () {
#Override
public void onResponse(Call < JSONObject > call, Response < JSONObject > response) {
}
#Override
public void onFailure(Call < JSONObject > call, Throwable t) {
}
});
RetrofitInterface
public interface RetrofitInterface {
#GET("ALE2")
Call<JSONObject> getData();
}
I don't want to store them in any model I just want to get the JSON as a string

Your interface should look like this :
public interface RetrofitInterface {
#GET("ALE2")
Call<ResponseBody> getData();
}
To get raw json object return type should be Call<ResponseBody>
Once that is done in response you can handle it like below :
retrofit.create(RetrofitInterface.class).getData().enqueue(new Callback<ResponseBody> () {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
String responseBody = response.body().string();
JSONObject json = new JSONObject(responseBody);
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
This is how you can set string in JSON object.

Related

Unable to send JSONObject using Retrofit POST?

So I have a JSONObject's object and I need to send the object to backend using Retrofit. It is a POST api and the body is of jsonObject. The following code I have written send JSONObject.
This is interface
public interface ApiSet {
#POST(Api.DELETE_EWAYBILL)
Call<JsonElement> deleteEwaybill(#Body JSONObject jsonObject);
}
This code I written in adapter
Call<JsonElement> call = ApiController.getInstance()
.getApi()
.deleteEwaybill(deleteEwayObj);
Log.e("vin1", deleteEwayObj.toString());
call.enqueue(new Callback<JsonElement>() {
#Override
public void onResponse(Call<JsonElement> call, retrofit2.Response<JsonElement> response) {
if (response.isSuccessful()) {
Gson gson = new Gson();
JsonElement jsonElement = response.body();
if(jsonElement.isJsonObject()){
JsonObject jsonObject = jsonElement.getAsJsonObject();
PostResponse postResponse = gson.fromJson(jsonObject, PostResponse.class);
if(postResponse.isSuccess()){
((Activity) context).recreate();
}else{
Toast.makeText(context,postResponse.getMessage(),Toast.LENGTH_LONG).show();
Log.e("vin1", "delete invoice error = "+postResponse.getMessage());
}
}
}
customProgressDialog.dismiss();
}
#Override
public void onFailure(Call<JsonElement> call, Throwable t) {
Log.e("vin1", "retrofit failure = " + t.getMessage());
customProgressDialog.dismiss();
t.printStackTrace();
}
});

Use GSON with Fast Android Networking library

I'm using https://github.com/amitshekhariitbhu/Fast-Android-Networking in my project.
Does it support GSON?
if yes how does it work with it?
I tried searching it in the documentation but it only contains information about JacksonParserFactory.
I found a GsonParserFactory in it
Using it like below
AndroidNetworking.setParserFactory(new GsonParserFactory());
but not sure how it works as I always get
org.json.JSONObject
You can use GSON to parse the JSON response to your Java Class Object
private Gson gson;
GsonBuilder gsonBuilder = new GsonBuilder();
gson = gsonBuilder.create();
//If your response id JSON array
AndroidNetworking.get("your_url")
.build()
.getAsJSONArray(new JSONArrayRequestListener() {
#Override
public void onResponse(JSONArray response) {
//For JSON array Response
List<YourModel> responseArray = Arrays.asList(gson.fromJson(response, YourModel[].class));
}
#Override
public void onError(ANError error) {
// handle error
}
});
//If your response is JSON object
AndroidNetworking.post("your_url")
.build()
.getAsJSONObject(new JSONObjectRequestListener() {
#Override
public void onResponse(JSONObject response) {
//For JSON object response
YourModel responseObject = gson.fromJson(response, YourModel.class);
}
#Override
public void onError(ANError error) {
// handle error
}
});

Implementing custom header for retrofit and i get No Retrofit annotation found, error

this below code is calling webservice which i want to implementing that with Retrofit on Android, but i get this error:
No Retrofit annotation found
calling Web Service with CURL:
curl -H "X-Auth-Token: 9HqLlyZOugoStsXCUfD_0YdwnNnunAJF8V47U3QHXSq" \
-H "X-User-Id: aobEdbYhXfu5hkeqG" \
http://localhost:3000/api/v1/channels.list
i wrote this interface like with above code:
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Header;
public interface RocketRestfulService {
#GET("/api/v1/channels.list")
Call<List<ChannelsList>> getChannelsList(
#Header("X-Auth-Token") String AuthToken,
#Header("X-User-Id") String UserId,
ChannelsList channelsList);
}
and i'm calling this rest Web Service by this code:
ChannelsList channelsList = new ChannelsList();
Call<List<ChannelsList>> call = rocketRestfulService.getChannelsList(
"HNv1VtMiyUky2RkXWUydyj4f2bfciQ6DzVQgKULSwfe",
"Wz9ex2N2z9zzJWdzD",
channelsList);
call.enqueue(new Callback<List<ChannelsList>>() {
#Override
public void onResponse(Call<List<ChannelsList>> call, final Response<List<ChannelsList>> response) {
Log.e("contentLength ", response.code() + "");
}
#Override
public void onFailure(Call<List<ChannelsList>> call, Throwable t) {
t.printStackTrace();
}
});
whats problem of my code that i can't call and i get error?
You forgot #Body annotation. And since you have to send a body, you must create a POST to your API. If is not a POST, you must find how to send ChannelsList in order to be a GET request because is depending your server implementation.
#POST("/api/v1/channels.list")
Call<List<ChannelsList>> getChannelsList(
#Header("X-Auth-Token") String AuthToken,
#Header("X-User-Id") String UserId,
#Body ChannelsList channelsList);
problem solved by this below code:
interface:
public interface RocketRestfulService {
#GET("/api/v1/channels.list")
Call<ResponseBody> getChannelsList(
#Header("X-Auth-Token") String AuthToken,
#Header("X-User-Id") String UserId);
}
call request and get response:
ChannelsList channelsList = new ChannelsList();
Call<ResponseBody> call = rocketRestfulService.getChannelsList(
"HNv1VtMiyUky2RkXWUydyj4f2bfciQ6DzVQgKULSwfe",
"Wz9ex2N2z9zzJWdzD");
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, final Response<ResponseBody> response) {
if (response.isSuccessful()) {
try {
String jsonString = response.body().string();
JSONObject jsonObject = new JSONObject(jsonString);
JSONArray jsonarray = jsonObject.getJSONArray("channels");
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e("Err: ", t.getMessage());
}
});

retrofit calling json data but its response show null

Here is my code any one help, why it shows response is null? There is some mistake which I cannot found.
public void getAllTasksWithSuccess(){
String url = ""+ RetrofitClient.baseURL +"here is my service code ";
RetrofitClient.createRetrofitInstance();
Call<ResponseBody> call = RetrofitClient.getCallObject("getTodaysTask",url);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
Log.i("TAG",response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.i("tag2", "Failed : " + t.getMessage());
}
});
}
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String okhttp3.ResponseBody.string()' on a null object reference
at com.ra.ra.DashboardFragments.FragmentTasks$2.onResponse(FragmentTasks.java:83)
Add below class ServiceGenerator:
public class ServiceGenerator {
public static final String API_BASE_URL = AppConstants.BASE_URL;
private static OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
public static Retrofit retrofit = null;
private static Retrofit.Builder builder =
new Retrofit.Builder()
.baseUrl(API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create());
public static Retrofit retrofit() {
retrofit = builder.client(httpClient.build()).build();
return retrofit;
}
}
And use below ErrorUtils class to parse your response's errorBody:
public class ErrorUtils {
public static ResponseBody parseError(Response<?> response) {
Converter<ResponseBody, ResponseBody> converter =
ServiceGenerator.retrofit()
.responseBodyConverter(ResponseBody.class, new Annotation[0]);
ResponseBody error;
try {
error = converter.convert(response.errorBody());
} catch (IOException e) {
return new ResponseBody();
}
return error;
}
}
And now in your onResponse do as below:
public void getAllTasksWithSuccess(){
String url = ""+ RetrofitClient.baseURL +"here is my service code ";
RetrofitClient.createRetrofitInstance();
Call<ResponseBody> call = RetrofitClient.getCallObject("getTodaysTask",url);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if(response.isSuccessful()){
// here your response.body() will not be null
}else{
// here your response.body() will be null
// and here you might get your response in response.errorBody();
ResponseBody res= ErrorUtils.parseError(response);
System.out.println("Response is:"+ res.toString());
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.i("tag2", "Failed : " + t.getMessage());
}
});
}

Using retrofit to read string content from api

Currently, I am using Retrofit to get data from api. But the format of data is a bit different from other format such as :
["tayl",["taylor swift","taylor swift kanye west","taylor swift famous","taylor swift mp3","taylor lautner","taylor swift wiki","taylor swift 1989","taylor hill","taylor swift 2016","taylor kinney"]]
So, I want to ask for the best solution to parse values to get a list as below if I want to use retrofit:
"taylor swift","taylor swift kanye west","taylor swift famous","taylor swift mp3","taylor lautner","taylor swift wiki","taylor swift 1989","taylor hill","taylor swift 2016","taylor kinney"
The content of the file above is the data which GoogleAutoComplete Api returned for me with the link below :
http://suggestqueries.google.com/complete/search?client=firefox&q=tayl
I implemented the code as below but it is not good:
#Headers({
"Accept: application/json",
"Content-Type: application/json; charset=UTF-8"
})
#GET("complete/search?")
Call<ResponseBody> getAutoComplete(#Query(#Query("q")String query);
The below is response code which I am using:
autoCompleteCall = googleApi.getAutoComplete(client, keyword);
autoCompleteCall.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response != null &&
response.body() != null) {
System.out.println(" String response======= " + response.body().toString());
return;
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
But the responsebody returned for me is null.
Please help me in this case.
Thanks.
Define the API endpoint in an interface as follows:
#GET("complete/search")
Call<ResponseBody> getAutoComplete(
#Query("client") String client,
#Query("q") String query);
Make the network request as follows:
Call<ResponseBody> call = service.getAutoComplete("firefox", "tayl");
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
ResponseBody body = response.body();
try {
// autocompleteOptions => ["tayl",["taylor swift","taylor lautner",...
String autocompleteOptions = body.string();
JSONArray jsonArray = new JSONArray(autocompleteOptions).getJSONArray(1);
// list => "taylor swift","taylor lautner",...
ArrayList<String> list = GetAutocompleteOptions(jsonArray);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
}
});
private ArrayList<String> GetAutocompleteOptions(JSONArray jsonArray) throws JSONException {
ArrayList<String> list = new ArrayList<>();
if (jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
list.add(jsonArray.get(i).toString());
}
}
return list;
}

Categories

Resources