Android json parsing can get json response from ws calling from Retrofit? - android

I am using retrofit lib because it's giving fast response.
But why need always one model class corresponding one ws response of parsing/calling web service using retrofit. Is it possible to get json response directly in my program?

You can wrap your response inside Response and then access the JSON data using the following:
call.enqueue(new Callback<ResponseBody>() {
#Override
onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
// Do your success stuff...
} else {
try {
JSONObject jObjError = new JSONObject(response.errorBody().string());
Toast.makeText(getContext(), jObjError.getString("message"), Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
}

Yes, you can. Use this as your api call:
Call<ResponseBody> yourMethod(). Then in your onResponse callback you can get json response via response.body().string(). See javadoc.

Related

Retrofit 2 Returns Null When HTTP is 404

I have API which works well. I return some http codes from API such as 200, 404 etc.
Whenever I get 404 http code from API, retrofit doesnt give me the response that I posted from API. As an example, I changed 404 code to 200 from API file and retrofit showed me. When code is 404, retrofit desn't give me the response body and returns null. I also tried to use if(response.isSuccessful) but didnt work.
Here is my retrofit code:
call.enqueue(new Callback<JsonElement>() {
#Override
public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {
switch (response.code()){
case 404:
Gson gson = new Gson();
JsonElement successElement = response.body();
POJO_Response_Error_Message errorMessage;
errorMessage = gson.fromJson(successElement, POJO_Response_Error_Message.class);
Toast.makeText(MainActivity.this, "ERROR "+errorMessage.getMessage(), Toast.LENGTH_SHORT).show();
break;
case 200:
Toast.makeText(MainActivity.this, "200 success", Toast.LENGTH_SHORT).show();
// get response...
break;
}
}
#Override
public void onFailure(Call<JsonElement> call, Throwable t) {
Log.d("error_log", "Retrofit error");
}
});
Error:
POJO_Response_Error_Message.getMessage()' on a null object reference
SOLVE:
I found alternative solution. My custom response was in Retrofit's errorBody itself.
Gson gson = new Gson();
Type type = new TypeToken<POJO_Response_Error_Message>() {}.getType();
POJO_Response_Error_Message errorResponse = gson.fromJson(response.errorBody().charStream(),type);
Toast.makeText(MainActivity.this, "RESPONSE: "+errorResponse, Toast.LENGTH_SHORT).show();

Android Json parsing string cannot be converted to json object error

I want to send parameters such as username and password.
I got an error like String cannot be converted to jsonobject.
I dont know what this happening.Anyone pls help me my code is:
JSONObject obj=new JSONObject();
try{
obj.put("username","test");
obj.put("password","test");
} catch (JSONException e) {
}
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST,
urlJsonObj, obj, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
} catch (JSONException e) {
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq,json_obj_req);
}
There is nothing wrong with the way you are creating JSONObject and putting values in it. Make sure the response received is Json, because your onResponse method accepts JSONObject. You could be receiving String value as response, which could not be converted to JSONObject.
It looks like your response is actually a string and not a json object i.e. {"object":"value"} but rather "object:value". You need to sniff your response via either Stetho, Fiddler or reenact your request via Postman (or Fiddler)
======================
This doesn't answer your question, but this will help you tremendously and make your life easier.
Highly recommend using Gson and Retrofit to make HTTP requests and parse Gson objects easily.
https://github.com/google/gson
http://square.github.io/retrofit/

POST raw data Using Retrofit

I'm trying to POST raw data using Retrofit.
I found many solution to POST JSON in Body using volley but the data I'm sending is not JSON.
my data is : {project_purpose: [EXECUTION]}
while hitting from the postman, I'm getting the data but not in android.
Please suggest me how to do this.
I'm trying to send as string but getting 500 in error code
I've also send the data in JsonObject, but not working..
Here is my code to call..
String bodyST = "{project_purpose: [purpose]}";
OR
JsonObject data = new JsonObject();
JSONArray jarray = new JSONArray();
jarray.put("EXECUTION");
data.addProperty("project_purpose", String.valueOf(jarray));
Call<JsonArray> call = apiInterface.getData(mAuthToken, "application/json", bodyST);
try this
I was facing the same problem when trying to POST data in raw form only and for this, i have wasted my whole day after that I got my solutions.
Your API interface should be like this:-
#POST(Constants.CONTACTS_URL)
Call<Object> getUser(#Body Map<String, String> body);
In your class where you are calling this
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Constants.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiInterface apiInterface = retrofit.create(ApiInterface.class);
try {
Map<String, String> requestBody = new HashMap<>();
requestBody.put("email", "davinder.codeapex#gmail.com");
requestBody.put("password", "12345678");
Call<Object> call=apiInterface.getUser(requestBody);
call.enqueue(new Callback<Object>() {
#Override
public void onResponse(Call<Object> call, Response<Object> response) {
try {
JSONObject object=new JSONObject(new Gson().toJson(response.body()));
Log.e("TAG", "onResponse: "+object );
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(Call<Object> call, Throwable t) {
}
});
} catch (Exception e) {
e.printStackTrace();
}
Output
logcat:
Postman
Note:-i am not using any model class to get data after, retrieving data you can use anyway to store data.
Just send your body as string
#PUT("your-endpoint")
fun yourRequsetFunction(#Body body : String) :Response<YourResponseType>

Retrofit error message is broken

onResponse is called.
But response.isSuccessful() is false.
I want to watch error massage.
#Override
public void onResponse(Call<UserInfo> call, Response<UserInfo> response) {
if (!response.isSuccessful()) {
try {
Log.d("Success false", response.errorBody().string()); // letter broken!!
} catch (IOException e) {
e.printStackTrace();
}
return;
}
}
print :
{"error":"\ub85c\uadf8\uc778\uc774 \ud544\uc694\ud569\ub2c8\ub2e4."}
Why letter is broken?
I think the error message is UTF8 encoded string. You could decode it by URLDecoder.decode(s, s)
I fixed it!
I think of json data as a string data.
error massage is json data.
json data need convert.
Try this :
JSONObject jsonobject = new JSONObject ( response.errorBody().string());
Log.d("error",jsonobject.getString("error");

Get single JSON property value from response JSON using Retrofit 2

I am using Retrofit library (version 2.0.2 as of this writing).
I am making a GET call to a service which responds a big JSON object but I am only interested in one key:value pair in it.
How can I get just that instead of writing a whole new POJO class that matches the JSON response?
Example -
{
status_code: 34,
status_message: "The resource you requested could not be found.",
...,
...
}
I need only status code value (34 here).
Please note, I am just giving an example of this JSON object here. The real one I am dealing with is huge and I care about only one key:value pair in it.
Thanks in advance.
You can refer to the following:
#GET("/files/jsonsample.json")
Call<JsonObject> readJsonFromFileUri();
and
class MyStatus{
int status_code;
}
...
Retrofit retrofit2 = new Retrofit.Builder()
.baseUrl("http://...")
.addConverterFactory(GsonConverterFactory.create())
.build();
WebAPIService apiService = retrofit2.create(WebAPIService.class);
Call<JsonObject> jsonCall = apiService.readJsonFromFileUri();
jsonCall.enqueue(new Callback<JsonObject>() {
#Override
public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {
String jsonString = response.body().toString();
Gson gson = new Gson();
MyStatus status = gson.fromJson(jsonString, MyStatus.class);
Log.i(LOG_TAG, String.valueOf(status.status_code));
}
#Override
public void onFailure(Call<JsonObject> call, Throwable t) {
Log.e(LOG_TAG, t.toString());
}
});
...
Debug screenshot

Categories

Resources