How to put a string variable in JSONObject - android

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

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

Escape / encode double quotes in string before sending via post request

I'm sending string below from Android to web service using volley request
params.put("data", objData.toString());
objData.toString() -->
{"report_time":1413876429,"device_id":"13d404d1b3a38ffc","ads_info":"[{\"play_count\":\"26\",\"ad_id\":\"21\"},{\"play_count\":\"58\",\"ad_id\":\"37\"},{\"play_count\":\"14\",\"ad_id\":\"40\"}]"}
Server not accepting it due the \"
How to remove \ keeping the json correct ""
You are not using the web service correctly.
Possibly the service expects to see a JSON array instead of a string containing JSON. Assuming params is a JSONObject and objData is a JSONArray, use params.put("data", objData) instead of the toString() version you have now.
Escaping the double quotes with backslashes is the only way to do this in java.
One other option would be to put the String into some kind of text file that you would then read at runtime.

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

sending datasets with ksoap

In my app I have to send a big dataset back to our server for processing. I am using ksoap for all my requests to pull stuff from the server with your normal xml properties and attributes but in the one call I have to use a dataset to send information.
Is there anything in the ksoap library for android that makes this whole process easier?
basically right now I am just constructing this huge string with all these header,tags and a shcema
example:
String header = "<mmAps diffgr:id=\"mmApps"+String.valueOf(count)+"\" msdata:rowOrder=\"0\" diffgr:hasChanges=\"inserted\">\n";
String ecmmaID = "<ECMMAID>"+c.getString(c.getColumnIndex(Apparatus.APP_ECMMAID))+"</ECMMAID>\n";
etc..
String datasetToSend = header+ecmmaID+....;
and then I would make the request passing in the big string
Please tell me there is some sot of easier way to do this.
Also changing away from data sets is not a possibility since its out of my control
JSON is the best option that you can use easily with KSOAP. This would be structured and far more better than your generated string.
1. Make identical Model class in android and your server (C#.Net, Java, etc.)
// In Android
class MyData {
String someThing;
public getSomeThing() {}
//...
}
2. Encode that dataset to JSONArray in android using model class
// Create JSON Objects in loop for entire dataset
JsonObject jo = new JsonObject();
jo.add(myData.getSomthing());
// Add all JSON Objects in JSONArray
JSONArray jArray = new JSONArray();
jArray.add(jo);
3. Send this JSON as string using KSOAP
String toSendViaKsoap = jArray.toString();
4. Decode that string from json to list of model class on server.
Depending on your server language, decode that string and create objects of similar class of step 1 in native language here, and do whatever you want.
If you have .NET server application, there are lots of free libraries to dacode json inclulding builting json support as well. but I will prefer this one.
Hope this helps..:)

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

Categories

Resources