Sending JSONArray to RetroFIt in Android - android

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());

Related

get simple json object using retrofit 2

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

Convert POJO to JSON Retrofit in Android

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/

Send Json params to Volley library

anyone know how can I send a JSON param to Volley ? Seeing the library, I watch the methods getParams that return a Map , but I need to send a Json with the form
{"medias" : [1,2,3,4,5] }
but if I send it with the getParams method, my server receive some like this : "medias" : "[1,2,3,4,5]" (the second part as a string)
any help?
A JsonObjectRequest in Volley allows you to pass your JSONObject into the constructor. Just create a JSONObject, add your JSONArray and use it to create your JsonObjectRequest.
Here's an example of how to create a JSONArray:
https://stackoverflow.com/a/13468303/736496

Rest Client with AndroidAnnotations - "no suitable HttpMessageConverter..."

I want to send POST request to server. I have to pass JSON object as a parameter, and get JSON as a response, but I am getting this error:
org.springframework.web.client.RestClientException: Could not extract response: no suitable HttpMessageConverter found for response type [com.package.Response] and content type [application/octet-stream]
Code
Sending request:
#RestService
RestClient restClient;
...
String json = "{\"param\":3}";
restClient.getRestTemplate().getMessageConverters().add(new GsonHttpMessageConverter());
Response res = restClient.send(json);
RestClient
#Rest("http://my-url.com")
public interface RestClient
{
#Post("/something/")
Response send(String json);
RestTemplate getRestTemplate();
void setRestTemplate(RestTemplate restTemplate);
}
I'm using these JAR files:
spring-android-rest-template-1.0.0.RC1
spring-android-core-1.0.0.RC1
spring-android-auth-1.0.0.RC1
gson-2.2.2
What I'm doing wrong? When I change send parameter to JSONObject I am getting the same error.
Btw. AA docs are really enigmatic - can I use Gson anyway? Or should I use Jackson? Which file do I need to include then?
Thanks for any help!
You can use RestTemplate with either Gson or Jackson.
Gson is fine and easier to use of you have small json data set. Jackson is more suitable if you have a complex / deep json tree, because Gson creates a lot of temporary objects which leads to stop the world GCs.
The error here says that it cannot find a HttpMessageConverter able to parse application/octet-stream.
If you look at the sources for GsonHttpMessageConverter, you'll notice that it only supports the mimetype application/json.
This means you have two options :
Either return the application/json mimetype from your content, which would seam quite appropriate
Or just change the supported media types on GsonHttpMessageConverter :
String json = "{\"param\":3}";
GsonHttpMessageConverter converter = new GsonHttpMessageConverter();
converter.setSupportedMediaTypes(new MediaType("application", "octet-stream", Charset.forName("UTF-8")));
restClient.getRestTemplate().getMessageConverters().add(converter);
Response res = restClient.send(json);
I just had this problem. After several hours I realised that the class I was passing in to the RestTemplate.postForObject call had Date variables. You need to make sure it only contains simple data types. Hope this helps someone else!
I have to modify it little to work:
final List<MediaType> list = new ArrayList<>();
list.addAll(converter.getSupportedMediaTypes());
list.add(MediaType.APPLICATION_OCTET_STREAM);
converter.setSupportedMediaTypes(list);

Rest Client - how get JSONObject as a response?

I'm following this guide - https://github.com/excilys/androidannotations/wiki/Rest%20API and I am trying skip JSON<->POJO conversion and work on pure JSONObject (or gson's JsonObject). What should I write as an server's answer?
#Rest("url")
public interface JsonRest
{
#Get("/getjson")
JSONObject getTime();
// or... ?
#Get("/getjson")
ResponseEntity<JSONObject> getTime();
// or... ?
#Get("/getjson")
JsonObject getTime();
}
In all cases I am getting "{}" as a response, but it's contains correct data after POJO conversion. Which HTTPMessageConverter should I provide? Thanks for any help.
Simply add GsonHttpMessageConverter to RestTemplate and try this:
#Get("/getjson")
JsonElement getSomething();
I don't think this is supported by Spring Android RestTemplate by default. You should probably provide your own provider.
You could look at how GsonHttpMessageConverter is implemented here and then implement your own solution based on that.

Categories

Resources