How to convert Json string into Json Array in Android Studio Java - android

I have a Json String like below
["Monday","Tueday","wednesday","Thuesday","Friday","Saturday"]
What I want to do is send this Json String to a web server using the android studio volley library.
SO I keep getting this error
com.android.volley.ParseError: org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONArray
The string cannot be converted to JsonArray.
So I have 2 questions I need help with.
My first is how to convert string to JsonArray. For example below String.
["Monday","Tueday","wednesday","Thuesday","Friday","Saturday"]
My second question is about passing this Jason Array (once we create) to a web server. I was researching about the Hashmap but I don't know how to send the JsonArray in Hashmap.
I had a go with below code, but it did not work.
#Override
protected Map<String, String> getParams() throws AuthFailureError {
return super.getParams();
}
I don't know how to send JsaonArray in hashmap.
So Overall, I would like to send this above string to web server.

Supose that the name of string is myString.
rString = myString.replace('[','');
rString = rString.replace(']','');
rString = rString.replace('"','');
String split[] = rString.split(',').
Now you have an array called split with every position is a day.

Edit: This is for frist question
Use that
JSONArray yourJsonArray = JSONArray.fromObject(yourJson);

Answer to first question:
I think it's not the exact response from the server, and there's a HTML <br> tag in the response.
because the line Value <br of type java.lang.String cannot be... clearly contains string <br, try replacing the HTML tags and/or decoding/unescaping the HTML tags to plain text, AND then you can convert that plain JSON text to JSONArray.
this snippet might help you out with decoding the response:
String parsedReponse = Html.fromHtml(serverResponse).toString()
if (parsedReponse != null) parsedReponse = parsedReponse.trim();
Answer to second question:
check out OkHttp3 and Retrofit libraries, they're pretty popular and amazing.
those can help you send POST data to your server
hope that helped you :)

Related

JSONArray to JSONObject error from string using Gson

Many similar questions/answers out in SO but unfortunately I was unable to find an QA like mine that I could solve the problem with.
I have a function which accepts an array of objects. This array is changed to a string and then is supposed to return an JSONObject. The exact function is:
fun schoolsIdsToJson(schoolIds: ArrayList<Schools.schoolIds>): JSONObject {
val baseType: Type = object : TypeToken<ArrayList<Schools.schoolIds>>(){}.type
val gson = GsonBuilder().disableHtmlEscaping().create()
val json = gson.toJson(schoolIds, baseType) //, baseType
var jsonResp: String = json.toString()
jsonResp = jsonResp.replace("\"[{]", "{")
jsonResp = jsonResp.replace("[}]\"", "}")
Log.e("schoolsIdsToJson", jsonResp)
return JSONObject(jsonResp)
}
When I log jsonResp the string is [{"_id":626}] which is correct. But when I put the string into the JSONObject, it throws the error:
org.json.JSONException: Value [{"_id":626}] of type org.json.JSONArray cannot be converted to JSONObject
Now, I would expect this if I didn't change it to a string but when it's a string I'm confused as to why the error happens.
Any pointers of what I'm doing incorrectly?
Thanks,
^.^
UPDATE
Thx for everyone's help. The cause is that I was mixing things up. Took awhile for me to understand that. Here is the comment that sorted things out for me. Maybe it'll help someone else.
Again, you're mixing the things up: the variable is a Java string, but the data it holds is a JSON array that cannot be converted to a JSON object like that -- it is just illegal. Either make that method return JSONArray (or whatever appropriate from the org.json package; I haven't worked with it), or extract the first value from the result array (that does not make much sense in that code either)

Sending Integer to Json Call

Actually "Strictly speaking, json is untyped, so you can't send it as an integer, it has to be a string." is said in that question 2 YEARS AGO. So i wonder if there are any changes in JSON to get integer from a JSON Object. I try to call integer by this way;
static int versionCode=0;
jsonObject = new JSONObject(result);
JSONObject queryJSONObject = jsonObject.getJSONObject("query");
versionCode =queryJSONObject.getInt("versionCode");
And the JSON is like this;
{"query":{"versionCode":1,....}}
Can anything be done?
Thanks.
follow this Tutorial you can use getString() function to get value and latter you can convert it like this int foo = Integer.parseInt("1234"); in integer according to your need
JSON has a number element, see JSON.org
JSON is a sequence of characters. But I disagree that a number is a string in this context. IMHO for me a string is wrapped in double quotes (which a number isn't).
Your code should work: json.getInt("versionCode") Source from Android Developer

How to put a string variable in JSONObject

I have a JSONObject:
JSONObject data = new JSONObject("{\"alert\": \"The Mets scored!\", \"action\": \"com.vipulk.acuv.UPDATE_STATUS\",\"ph\": ph }");
I have a string defined as:
String ph="this is String";
Now when i receive this JSONObject on receiver side I have the value of "ph" as "ph". I want the value of original String ph. How to do it. Can JSONObject send extra strings with another method.
Pardon my limited knowledge about JSON, as I am using it just once so I am avoiding going deep. I have everything done except putting this string variable in JSONObject.
NOTE: I am working with PARSE push notifications and I've to send this object in a push notification (that i am able to do).
If you want to modify your JSONObject, you can use .put method (http://json.org/javadoc/org/json/JSONObject.html#put%28java.lang.String,%20java.lang.Object%29):
data.put("ph", ph);

Adding link to json object in android

JSONArray albumarray=new JSONArray();
JSONObject imgobj=new JSONObject();
imgobj.put("thumb", filepath.get(i));
imgobj.put("main", filepath.get(i));
albumarray.put(imgobj);
JSONObject albumjson=new JSONObject();
albumjson.put(albumname,albumarray);
When I convert albumjson to string using
albumjson.toString()
I am getting output as below.
{\"test2\":\"[{\\\"thumb\\\":\\\"http:\\\\\\/\\\\\\/dev.mysite.in\\\\\\/mysite\\\\\\/sites\\\\\\/default\\\\\\/files\\\\\\/512da541b31fe.jpg\\\",\\\"main\\\":\\\"http:\\\\\\/\\\\\\/dev.mysite.in\\\\\\/mysite\\\\\\/sites\\\\\\/default\\\\\\/files\\\\\\/512da541b31fe.jpg\\\"}]\"}
the correct format i need is
{"test2":[{"thumb":"http://dev.mysite.in/mysite/sites/default/files/512d9bdced1f2.jpg","main":"http://dev.mysite.in/mysite/sites/default/files/512d9bdced1f2.jpg"},{"thumb":"http://dev.mysite.in/mysite/sites/default/files/512d9be134cb8.jpg","main":"http://dev.mysite.in/mysite/sites/default/files/512d9be134cb8.jpg"}]}
How to replace additional slashes.
PLease use JSONObject.getString('keyName') method instead of toString()
EDIT:
You should first understand why those extra \\ are showing up.It is an escape character for ".Hence,it is very much required there and is a part of JSON encoding .Hence,one should always use the above method to get values of keys whenever needed.
apart from that you can try :
JSONObject.toString(4) where 4 is actually indent spaces and see whether it helps.Otherwise there's simply no other option than to replace those extra \\ like
myJsonString.replaceAll("\\","");
or
myJsonString=myJsonString.replaceAll("\\\\","");
SECOND EDIT:
The string you are sending is perfect to send to any server.You need to decode that string at the server end to JSON and then utilise it.
If you are using .NET you can see this. Or if you are on some other platform you need to find out how to decode to JSON on that platform.
There are two things going on here:
Your tools are confusing you. When it shows the output:
"{\"test2\":\"[{\\\"thumb\\\":\\\"http:\\\\\\/\\\\\\/dev.lrcdn.in\\\\\\/shiaspark\\\\\\/sites\\\\\\/default\\\\\\/files\\\\\\/512da541b31fe.jpg\\\",\\\"main\\\":\\\"http:\\\\\\/\\\\\\/dev.lrcdn.in\\\\\\/shiaspark\\\\\\/sites\\\\\\/default\\\\\\/files\\\\\\/512da541b31fe.jpg\\\"}]\"}"
It is telling you that the result is a string containing:
{"test2":"[{\"thumb\":\"http:\\\/\\\/dev.lrcdn.in\\\/shiaspark\\\/sites\\\/default\\\/files\\\/512da541b31fe.jpg\",\"main\":\"http:\\\/\\\/dev.lrcdn.in\\\/shiaspark\\\/sites\\\/default\\\/files\\\/512da541b31fe.jpg\"}]"}
Taking that string and formatting it:
{"test2":
"[{\"thumb\":\"http:\\\/\\\/dev.lrcdn.in\\\/shiaspark\\\/sites\\\/default\\\/files\\\/512da541b31fe.jpg\",\"main\":\"http:\\\/\\\/dev.lrcdn.in\\\/shiaspark\\\/sites\\\/default\\\/files\\\/512da541b31fe.jpg\"}]"
}
We can see that you've constructed a json object containing a json-encoded string, rather than a nested jsonobject. For whatever reason, your code is having the effect of:
JSONArray albumarray=new JSONArray();
JSONObject imgobj=new JSONObject();
imgobj.put("thumb", filepath.get(i));
imgobj.put("main", filepath.get(i));
albumarray.put(imgobj);
JSONObject albumjson = new JSONObject();
albumjson.put(albumname, albumarray.toString());
That sounds like a bug in your json library

About JSONArray exception on Android (and the max size of a string)

I'm developing an Android (2.2) application in which I get from a web service a string containing the JSON serialized version of a list of custom objects, which results in a JSONArray string of JSONObject. The received string is well formed, as I can see at eyesight and as I can prove with online validator. At one point in the Android application, I pass this string to a JSONArray constructor, to get an array of JSONObject. Here's the problem: the JSONArray constructor throws an exception, stating that at some point the string ends with a invalid terminator: but the point indicated in the exception is far from the real end of the string. The fact is that the string in question is huge (about 160000 chars): does anyone know if there's a limit to the length of a string when passed to the JSONArray constructor? The string variable held in memory is full-length, so it seems to me that the JSONArray constructor kindof truncates it. Is it possible?
Thanks in advance,
regards
Try removing the spaces at the end of the string if any and parse again.
Use trim() on string and check once.
Ok guys, it's all my fault. I read the string from an http stream and I did not realize that sometimes I get the string when it's not completed (hence the exception which I tought to be be JSONArray fault).

Categories

Resources