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.
Related
My project have the following structure:
Activity>ViewModel>UseCase>Repository>WebService
The WebService class call an api and receive the json that i need to parse to my object, where i should do this parse?
I'm returning from the WebService an default object that contains 2 properties: statuscode and json until my use case, where i parse the json and return the object to the ViewModel, is that wrong?
I'm using Retrofit to get some data from a server. The problem is the response body is null (although I get a response code : 200 ) and if you check this github issue like I did you will see that they suggest you to use Call<Void> for empty response's body.
I did change it to Call<Void> and now when I'm making a request with Retrofit it enters onResponse and response is successful, but then I can't deserialize it with Gson.
Using :
DataServiceResponse serviceResponse = gson.fromJson(response.body(), DataServiceResponse.class);
is not possible since response.body() is void.
Is there any simple way in Retrofit to convert passed object to JSON automatically?
This is my Retrofit interface :
#FormUrlEncoded
#POST("/places/name")
void getPlacesByName(#Field("name") String name,
#Field("city") String city,
#Field("tags") Tags tags,
Callback<PlaceResponse> callback);
At first I thought that if I pass Tags object it will be automatically converted to JSON , but in reality request looks like this :
name=pubs&city=London&tags=com.app.database.model.Tags%4052aa38a8
Is there any simple way to convert POJO to JSON in Retrofit?
You are creating a URL with parameters because you're using the #URLEncoded and passing the parameters as #Field.
Here is the solution:
#POST("/places/name")
void getPlacesByName(#Body RequestObject req, Callback<PlaceResponse> callback);
Additionaly, I would advise on using #GET for retrieving objects. #POST is used for creating an object and #PUT for updating. Although this isn't wrong, it as recomendation in order be RESTful compliant.
Use Jackson to convert it directly to a String:
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = ow.writeValueAsString(object);
Or use Gson: http://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/
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 am trying to parse a response from server and i am new to this topic, Unfortunately it is in JSONP format. I don't know how to parse JSONP format, when i tried with JSON Parser it is returning null value.
Can anyone please help me in doing this...
Thanks in Advance.
JSONP is just JSON wrapped in a JavaScript function call. For instance, something like:
callback({"status":"success", "someVar":1});
So you have a couple of options. If you are using a WebView you can define a function called callback in JavaScript and then just call eval() on the JSONP data. This will invoke the callback function, passing it the parsed JSON object (the eval() does the parsing for you).
Or, if you have the JSONP string in your Java code, the simplest option is probably to extract out the JSON substring, like:
String json = jsonp.substring(jsonp.indexOf("(") + 1, jsonp.lastIndexOf(")"));
That will strip off callback( and );, leaving you with just {"status":"success", "someVar":1}, which should then parse with any standard JSON parser.