Sending Integer to Json Call - android

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

Related

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

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 :)

Iterating through JsonObject in Java/Android. NOT JsonArray

Here's my JSON data sample:
{
"node_1.1":{
"someCrap":{
"someCrap":"SomeValue"
}
},
"node_1.2":{
"Node_1.2.1":{
"Node_1.2.1.1":{
"param1":value,
"param2":value,
"param3":"value",
"paramThatIneed":{
"ThisIsWhatIActuallyNeed":"url",
"width":96,
"height":72
}
},
"Node_1.2.1.2":{
Same as above, just that paramThatINeed might be missing, gotta place imagePlaceHolder Here
},
//and so on... there are a total of 50 of these..
}
}
}
Now I could get the node_1.1 and Node 1.2 and the sub-node of it node_1.2.1
However, there are 50 sub-nodes inside of node_1.2.1, and they will have random names returned from the server. Its in string format but they're actually ints. Its a page ID.
Now I wanna iterate through the node_1.2.1 and get those sub-nodes and access their sub-nodes and take in the URL of the paramThatINeed. If the paramThatINeed is not present, I need to put some null/dummy value.
This is the code that I tried to work it as far as I've reached:
JSONObject jsonObj = new JSONObject(jsonStr); //jsonStr is the entire JSON string
JsonObject node_1.2= jsonObj.getJsonObject("node_1.1");
JsonObject node_1.2.1 = node_1.2.getJsonObject("node_1.2.1");
What do I do after this? Because I can only getJsonObject by passing a string param to it, I tried using the for loop but it doesn't take any int param.
Also, as I said before, the nodes after that have random names and not fixed. So I'm totally confused.
Please help me out if you know how to solve this problem. Please remember there's no JsonArray in this. I'm probably thinking of editing the JSON string itself and replacing some parts of the '{' with '[' and converting it to an array :( ... I think that's a sad approach.
Use this to iterate over an object.
Android (JSONObject) How can I loop through a flat JSON object to get each key and each value
but be careful, from json object you won't get the result in original order, like in json array. The result will be in alphabetical order (I hope I was clear). And you can use optJsonobject(), instead of getJsonObject(). It will returns null, instead of throw exception. You can use opt every where instead of get.

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

How to process an array returned by a wsdl?

I am using ksoap2 in order to extract an array of strings from a wsdl based webservice(for an android app). How do I process the returned array? I need those 3-4 lines of code which will let me save and use that returned array in my class. Thanks.
String r = NameArray.columncount("userid", limitstart, loadNumber,loggername);
String temp = r.replaceAll(";\\s", ",").replaceAll("string=", " ")
.replace("anyType{", "").replace(",}", "");
String[] fulname = temp.split(",\\s+");
'NameArray.columncount' is my function which gets the array from the wsdl(don't get confused in that)
step 1-
Here I am getting the array values returned from the wsdl in to a string called 'r'.In this case I am getting an array of numbers
Returned array string r looks like this
r ="anyType{string=10054; string=10055; string=10056; string=10035; string=10052; string=10036; string=10037; string=10038; }"
step 2-
Then creating a String variable called temp where I am removing all the unwanted characters using the replaceAll function.
after removing unwanted characters temp looks like this
temp="10054, 10055, 10056, 10035, 10052, 10036, 10037, 10038"
step3-
Finally created a string array called 'fulname' and split the modified string with ',\s'
Array fulname after split looks like this
fulname = [ 10054, 10055, 10056, 10035, 10052, 10036, 10037, 10038]
This will work fine because all the wsdl array return the same type of string with same unwanted characters
Hope you understood
Good Luck
If you are still on this problem, you can check out this article which explain the whole procedure to parse arrays returned in KSOAP:
http://seesharpgears.blogspot.fr/2010/10/web-service-that-returns-array-of.html
Hope this answer to your question ;)

Categories

Resources