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.
Related
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.
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.
Im using JsonObject to parse a response from an API, the problem is that the resulting String have double quotes, how to get string with no quotes?
JsonElement jelement = new JsonParser().parse(response);
JsonObject jobject = jelement.getAsJsonObject();
String authorization = jobject.get("authorization").toString();
Log.d("mensa","parseado jwt :"+authorization);
so my response looks like...
parseado jwt :"eyJ0eXAiOiJKV1QiLCJhbGciO..."
Actual Json response
{
"authorization": "eyJ0eXAiOiJKV1..."
}
what is the right way to parse this string so i dont get it wrapped with double quotes?
I believe you are using GSON library. No need to trim out your result, gson provide methods for that. try this
String authorization = jobject.get("authorization").getAsString();
Refer Gson API Doc : JsonElement
You are getting Object from Json and then converting to String. jobject.get("authorization").toString(); try to get String.
String authorization = jobject.getString("authorization");
Just trim out the quotes: authorization = authorization.substring(1, authorization.length() - 1)
Edit: You should actually use the getString() method as it will return the actual content as a string, however, the above still works as a quick workaround.
I am using Volley with GSON and I need to send a object as a parameter to my call.
This is how I do the object:
JSONObject params = new JSONObject();
Gson gson = new Gson();
String json = gson.toJson(route);
params.put("route", json);
And then I call my Volley JsonObjectRequest function.
The problem is that the params look like this:
{"route":"{\"bounds\":{\"northeast\":{\"lat\":52.3777194,\"lng\":4.924666999999999},\"southwest\":{\"lat\":52.36881109999999,\"lng\":4.9011479}},\"copyrights\":\"Map data ©2014 Google\", etc...}"
As you can see, instead of sending it as a object, its sending it as a String , and that's why I get the " before the {} (before the object begins). The params should look like:
{"route":{\"bounds\":{\"northeast\":{\"lat\":52.3777194,\"lng\":4.924666999999999},\"southwest\":{\"lat\":52.36881109999999,\"lng\":4.9011479}},\"copyrights\":\"Map data ©2014 Google\", etc...}
So no " before { like this:
{"route":{myObject}
What an I doing wrong here?
You don't want to mix JSONObject and GSON.
That's 2 different libraries.
Use gson.toJsonTree to obtain an element, then use JsonObject instead of JSONObject:
JsonObject params = new JsonObject();
Gson gson = new Gson();
params.add("route", gson.toJsonTree(route));
I know how to access to json. Now I get a json response like that:
"2014-02-16T20:27:54+00:00"
https://openligadb-json.heroku.com/api/last_change_date_by_league_saison?league_shortcut=bl1&league_saison=2013
this is not a JSONArray and has no Name. How can I access it?
It is not json formatted data. If you need it in json, you can generate it by yourself like this :
JSONObject json = new JSONObject();
json.put("data", "2014-02-16T20:27:54+00:00" );
json.toString(); // { "data" : ""2014-02-16T20:27:54+00:00" } it is json
In other case you can work with this data as typical String. It depends on what you need to achieve.
Good luck!