Getting different Json Array element Order in Retrofit and Postman - android

I hit same API from Postman & Retrofit. Postman returns correct JSON array elements order but in Retrofit i get shuffled results.
I am expecting the same JSON array element order in retrofit as i get in postman.
POSTMAN parameters
{
"campusId":1,
"reported":true,
"size":30,
"status":[5,6,7,8],
"sortBy":"updatedAt",
"sortDirection":"desc",
"page":1
}
Retrofit Parameters
Map<String,Object> body = new HashMap<>();
body.put("campusId",1);
body.put("reported",true);
body.put("size",30);
body.put("status", Arrays.asList(5,6,7,8));
body.put("sortBy ","updatedAt");
body.put("sortDirection","desc"); //desc
body.put("page",1);

Related

Response Code 400 Bad Request when use Json String param in Query tag Retrofit 2 Android

I'm using Retrofit 2 to call API in Android App. I have a API, using POST, which have a String param in Query Tag. I do everything like doc suppose and I test this API successfully in Test Page. I can run another API correctly so the problem is not the way I use Retrofit 2.
Here is my interface:
#POST("/users/{userId}/get_list_friends")
Call<GetListFriendDataResponse> getListFriend(#Path("userId") int userId, #Query("list") String list, #Query("page") int page, #Query("size") int size, #Header("hash") String hash);
Here is my implementation:
ArrayList<String> id = new ArrayList<>();
id.add("4782947293");
JSONArray jsonArray = new JSONArray(id);
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("list", jsonArray);
} catch (JSONException e) {
e.printStackTrace();
}
String list = jsonObject.toString();
Log.e(TAG, "list: " + list);
apiInterface.getListFriend(21, list, 1,1,"AHHIGHTJGI").enqueue(new Callback<GetListFriendDataResponse>() {
#Override
public void onResponse(Call<GetListFriendDataResponse> call, Response<GetListFriendDataResponse> response) {
Log.e(TAG, " response code: "+ response.code());
}
#Override
public void onFailure(Call<GetListFriendDataResponse> call, Throwable t) {
}
});
I always get response code: 400 when use this API.
I'm focusing the "list" var. "list" is a JSON text but I wonder if method "jSon.toString()" is right to get a String from a JSONObject, which can using in Retrofit 2. List param form is:{"list":["12332"]} .
Please help me!
Questions
1) Why you are creating JSONObject and JSONArray on your own?
2) You are creating string using whatever you are creating json.
Eg: {list:["123","456"]}
you are trying pass whole json, I think, instead you need to pass just the array of string to the list key.
Request Sending
{
list:["123","456"]
}
suppose the above json is the request you want to send to server
Now, create model class goto http://jsonschema2pojo.org and paste your json and select json and gson at right side and click on preview.
It will show the classes to map you json to model. Use this model class to set the list to the key in your json
I found my problem. The JSON text contains some special character so I need to convert them to URL encode.
Correct request URL like this:
http://54.169.215.161:8080/users/29/add_friend?list=%7B%22list%22%3A%5B%2215536%22%5D%7D&platform=google
By using Retrofit 2, it uses the URL:
http://54.169.215.161:8080/users/29/add_friend?list={%22list%22:[%2215536%22]}&platform=google
So I get Bad Request Response code.
Retrofit 2 also provides method to convert char sequence to URL encode but it 's not enough. So I don't use Retrofit 's convert method by using this code: encode= true.
so my interface is:
#POST("/users/{userId}/get_list_friends")
Call<GetListFriendDataResponse> getListFriend(#Path("userId") int userId, #Query(value = "list",encoded = true) String list, #Query("page") int page, #Query("size") int size, #Header("hash") String hash);
And I manually convert JSON text to URL encode by code:
list = list.replace("{", "%7B");
list=list.replace("]", "%5D");
list=list.replace("[", "%5B");
list=list.replace(":", "%3A");
list=list.replace("}","%7D");
list = list.replace("\"", "%22");
That's all. Now I can get data by using API.
Suggestion: If u have the same problem, check the URL retrofit return in response and compare to correct URL to see special character, which is not converted to URL encode.

Retrofit adding extra slash to the serialized JSON multipart string

I believe it's Retrofit that's adding the extra slash to the key value pairs when calling the service with serialized JSON data.
I have a hash map object to be passed as a multipart string, and I'm converting it to JSON string using Gson.
public static String getJsonString(Object object) {
gson = new Gson();
jsonString = gson.toJson(object);
return jsonString;
}
I have the retrofit builder like
Retrofit.Builder()
.baseUrl(path)
.addConverterFactory(GsonConverterFactory.create())
.client(trustCert(context))
.build();
Passing the JSON data as
Call<ResponseBody> responseBodyCall = ApiClient.getInstance(context).getApiService().uploadData(getJsonString(params));
Api interface:
#Multipart
#POST("upload")
Call<ResponseBody> uploadData(#Part("data") String data);
When we debugged on the server side, the received json data has extra slashes in it. For example, it's supposed to be like \"{\"key1\", \"value\"}\" but it is being serialized as \\"{\\"key1\\", \\"value\\"}\\". I have put a breakpoint just before the api call, and the data is all good, but on the server side it's weird.

Directly POST JSONObject via retrofit

Can I send JSON directly via retrofit like this:
#POST("rest/workouts")
Call<CreateWorkoutSuccessAnswer> createWorkout(#NonNull #Body JSONObject jsonObject);
You can use TypedInput
#POST("rest/workouts")
Call<CreateWorkoutSuccessAnswer> createWorkout(#NonNull #Body TypedInput body);
And to form param:
TypedInput in = new TypedByteArray("application/json", jsonObject.toString().getBytes("UTF-8"));
And use in as a parameter for request.
You can directly post JSON objects using GSONs JsonObject class.
The reason Googles JSONObject does not work is that retrofit uses GSON by default and tries to serialize the JSONObject parameter as a POJO. So you get something like:
{
"JSONObject":
{
<your JSON object here>
}
}
If what you are doing requires you to use JSONObject then you can simply convert between the two using the String format of the object.

Retrofit parse array of strings

I have troubles with parsing of server response using retrofit. Server returns array of strings, how it's possible to parse this: ["1", "21", "22"] using retrofit framework. I'm using Retrofit 2.0.0-beta2.
Thanks
To parse that response define your method in API interface like this:
#GET("methodThatReturnsArray")
Call<ArrayList<String>> methodThatReturnsArray();
Synchronous call would look like
Call<ArrayList<String>> call = retrofitService.methodThatReturnsArray();
Response response = call.execute();
ArrayList<String> arrayOfStrings = response.body();

Android client error with returning valid JSON from Django server

I am hoping someone might be able to help me out.
I have a Django server that is returning JSON to an iOS application. On the Django server, we are using
return HttpResponse(json.dumps(session_dict),mime_type)
to return the JSON to the client as (via Wireshark)
2f
{"session": "bcb493fb21ae8fcd9152e1924b3e5d9a"}
0
This response is somehow valid to the iOS application able to be parsed by the iOS JSON client libraries. This does not look like valid Json to me so I am surprised it works.
However, if I use the following in Android, I get an error:
Value session of type java.lang.String cannot be converted to JSONObject.
jsonObjSend.put("username", strUserName);
jsonObjSend.put("password", strPassword);
Add a nested JSONObject (e.g. for header information)
JSONObject header = new JSONObject();
header.put("deviceType","Android"); // Device type
header.put("deviceVersion","2.0"); // Device OS version
header.put("language", "es-es");
jsonObjSend.put("header", header);
// Output the JSON object we're sending to Logcat:
Log.i(TAG, jsonObjSend.toString(2));
} catch (JSONException e) {
e.printStackTrace();
}
try {
// Send the HttpPostRequest and receive a JSONObject in return
JSONObject jsonObjRecv = HttpClient.SendHttpPost(URL, jsonObjSend);
String sessionId = jsonObjRecv.getString("session");
Any suggestions?
Thank you,
Greg
Does your HttpClient.sendHttpPost method return a JSONObject? Not sure if it parses the response body from the HTTP POST into a JSONObject automatically. If it doesn't, then you would have to do that using the JSONTokener or use a library like Gson.
google's GSON may be a better choice you can convert an instance to json string directly such as
User user =new User("tom","12");
Gson gson =new Gson();
json=gson.toJson(user);

Categories

Resources