My api prints a simple json object like this:
{"status":1}
How to say that retrofit (v2) pass it to gson and return an JSONObject contains this key-value pair in response?
I tried following:
Call<JSONObject> result();
But when prints response.body() in onResponse (Response<JSONObject> response) method, it returns {} which means it's empty.
After lots of R&D I got answer. Please find it below
Use JsonObject from package com.google.gson instead of JSONObject from package org.json
After that call Call<JsonObject> result() and in onResponse (Response<JsonObject> response) method used to call response.body() or response.body().toString(); it wil print correct Json from apiwhatever you want
To get org.json.JSONArray or org.json.JSONObject just create custom ConverterFactory like here:
https://github.com/marcinOz/Retrofit2JSONConverterFactory
Related
I have a generic method getData that should get from the server some POJOs of different objects. Before Retrofit 2.6 without coroutines I could create a method like this:
#POST("GetData")
fun getGenericData(#Query("sessionId") sessionId: UUID, #Body request: RemoteRequest): Call<ResponseBody>
An it was fine because I could handle the json contained in the body and deserialize it based on the object name declared in a property inside the json, but with Retrofit 2.6 and coroutines that is not possibile because the return type Call or ResponseBody throw an exception. I do not want to use Response because I do not know the type of the object at compile time and I want to deserialize the returned json separately. Any idea ?
I am using Retrofit for server calls. I need to send a JSONArray to the server. My JSONArray looks like -
[{"callName”:”xxx”},{“inputData":{"deviceImei”:”xxxx”,”appVersionUser”:”x”,”osVersion”:”x”,”osType”:”x”,”deviceToken”:”xxxx”}}]
I am using RetroFit version 1.9.0 . I tried to use #BODY. But I am getting this error -
retrofit.RetrofitError: APIClass.GetClientAuthentication: #Body parameters cannot be used with form or multi-part encoding"
My Api function declaration is,
#FormUrlEncoded
#POST("/XYZ")
void GetClientAuthentication(#Body JSONArray jArray,
Callback<AuthenticationCallBack> aPOJOCallback);
Can anybody help?
Thanks in advance.
Hey i solved it finally
At the receiving part i took response in JSONElement and converted it to POJO class like below. AuthenticationErrorJsonResponse.java is my POJO class.
ArrayList<AuthenticationErrorJsonResponse> yourArray = new Gson().fromJson(authenticationJsonResponse.toString(),
new TypeToken<List<AuthenticationErrorJsonResponse>>(){}.getType());
I am using Retrofit to hit an api. I need to get both Json and header response. So my interface method is like this. So in Response type Object I get response header from response.getHeaders(). But when I try to get the json response from response.getBody(), I don't get a proper response. I need help in fetching and parsing the json response from the Response object :-(
#GET("/api/hello/categories")
retrofit.client.Response getData();
getBody() doesn't return a String directly, you'll have to convert it yourself if you don't want to user Retrofit's built converters.
This link should be a simple way to grab the String from the response, and you can parse it accordingly.
I'm trying to POST a JSONObject using the Retrofit library, but when I see the request at the receiving end, the content-length is 0.
In the RestService interface:
#Headers({
"Content-type: application/json"
})
#POST("/api/v1/user/controller")
void registerController(
#Body JSONObject registrationBundle,
#Header("x-company-device-token") String companyDeviceToken,
#Header("x-company-device-guid") String companyDeviceGuid,
Callback<JSONObject> cb);
And it gets called with,
mRestService.registerController(
registrationBundle,
mApplication.mSession.getCredentials().getDeviceToken(),
mApplication.mSession.getCredentials().getDeviceGuid(),
new Callback<JSONObject>() {
// ...
}
)
And I'm certain that the registrationBundle, which is a JSONObject isn't null or empty (the other fields are certainly fine). At the moment the request is made, it logs out as: {"zip":19312,"useAccountZip":false,"controllerName":"mine","registrationCode":"GLD94Q"}.
On the receiving end of the request, I see that the request has Content-type: application/json but has Content-length: 0.
Is there any reason why sending JSON in the body like this isn't working? Am I missing something simple in using Retrofit?
By default, you don't need to set any headers if you want a JSON request body. Whenever you test Retrofit code, I recommend setting .setLogLevel(RestAdapter.LogLevel.FULL) on your instance of RestAdapter. This will show you the full request headers and body as well as the full response headers and body.
What's occurring is that you are setting the Content-type twice. Then you're passing a JSONObject, which is being passed through the GsonConverter and mangled to look like {"nameValuePairs":YOURJSONSTRING} where YOURJSONSTRING contains your complete, intended JSON output. For obvious reasons, this won't work well with most REST APIs.
You should skip messing with the Content-type header which is already being set to JSON with UTF-8 by default. Also, don't pass a JSONObject to GSON. Pass a Java object for GSON to convert.
Try this if you're using callbacks:
#POST("/api/v1/user/controller")
void registerController(
#Body MyBundleObject registrationBundle,
#Header("x-company-device-token") String companyDeviceToken,
#Header("x-company-device-guid") String companyDeviceGuid,
Callback<ResponseObject> cb);
I haven't tested this exact syntax.
Synchronous example:
#POST("/api/v1/user/controller")
ResponseObject registerController(
#Body MyBundleObject registrationBundle,
#Header("x-company-device-token") String companyDeviceToken,
#Header("x-company-device-guid") String companyDeviceGuid);
I got the following request from an Android developer:
Would you change the webservice back-end so that it returnes empty
strings for empty fields instead of null.
The Android json parser converts null to a string containing "null".
The code:
import com.google.gson.Gson;
//...
private OrganizationSearchResult result;
//...
Gson gson = new Gson();
result = gson.fromJson(resultString, OrganizationSearchResult.class);
Is this a known issue?
If so, is there a known work-around for it?
I dont know what you are using for parsing the json and the JSONObject class in android sdk doesnt do that.
Take a look at the following class
http://developer.android.com/reference/org/json/JSONObject.html
Check out has and isNULL of the above method.
I think GSON automatically handles the null in json by converting them to java null.
there will be a method isNull(key) in jsonObject to Determine if the value associated with the key is null or if there is no value, check with this and then call getString(key).