Android JsonObject parsing string with double quotes - android

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.

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.

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.

android: json response is just a String

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!

Json with RabbitMQ

I have a problem sending Json messages with RabbitMQ using Android.
I have to parse RabbitMQ object to string and bytes to send the message
channel.basicPublish("", Cola_RPC, props, mensaje_parseado.toString().getBytes()); //Mensaje_parseado is the Json
When I recive the message I don't know how to parse into Json again to get the original message.
I try:
String stringJSON = delivery.getBody().toString();
JSONObject respuesta_desparseada = new JSONObject (stringJSON);
But it doesn't work.
Maybe is a noobie question, but I can't reach the soluction on Google.
Thank you in advance.
You need to change this:
String stringJSON = new String(delivery.getBody());
JSONObject respuesta_desparseada = new JSONObject (stringJSON);
You are calling toString() in a byte[] that uses the toString() method from Object.
If you want to see why, you can run this:
String myString = "myTest";
System.out.println(myString);
System.out.println(myString.getBytes());
System.out.println(myString.getBytes().toString());
System.out.println(new String(myString.getBytes()));

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