JSONArray to JSONObject error from string using Gson - android

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)

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.

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

JSONException: java.lang.String cannot be converted to JSONObject

I know this question has been asked a number of times but I didn't find any relative answer of my question.
I am trying to read json data from asset folder, but I'm getting following exception while getting
I searched number of stuffs but didn't help. Please give me any reference or hint.
Thanks in Advance.
Use
String searchedTerm = jsonObject.getString(TAG_SEARCHEDTERM);
JSONArray results = jsonObject.getJSONArray(TAG_RESULTS);
instead of
JSONObject searchedTerm = jsonObject.getJSONObject(TAG_SEARCHEDTERM);
JSONArray results = searchedTerm.getJSONArray(TAG_RESULTS);
because TAG_SEARCHEDTERM is key-value pair instead of JSONObject and you are trying to cast a String value to JsonObject.
I guess you need to get the Dish Name where you are getting exception.
You can get the dish name shown below...
String searchedTerm = jsonObject.getString(TAG_SEARCHEDTERM);
Using this
JSONArray results = jsonObject.getJSONArray(TAG_RESULTS);
you will get the "results" JSONArray as shown in your json file.
and you can iterate through it using for loop.

Accessing an object from JSON in Android

I have a question that I am a little bit confused about. I am quite new to JSON and getting JSON values in the android API. I am trying to access an array within the response I get. the JSON code I am getting is something like this:
Response:
{
"event": {
"participants": []
},
"status": "success"
}
How would I access the participants array and store their values. This is what I am trying at the moment... but I dont appear to be getting what I want.
try{
//get the JSON values from the URL.
JSONObject json = jParser.getJSONFromUrl("http://somesite.com/api/find?"+"somevar="+someJavaStringVar);
json_event = json.getJSONObject("event");
JSONArray json_array_participants = json_event.getJSONArray("participants");
} catch(JSONException e) {
}
The thing I am mostly confused about is... what is the arrays type equivalent to. Any advice or reasoning as to the correct way to get ahold of that variables value would be great... thanks guys.. :).
Think JSON is really just a key-value pairing. The JSONArray type is just an array full of objects (like Object[]) - it has no idea what the objects it contains are or what they're to be used for. Its up to you to assign meaning to the JSON stream based on what you know of the source. From what I see of your code, most of it looks fine, though I don't know what your jParser.getJSONFromURL() is doing. Typically, you would build the JSON from the response string like so:
String jsonString = getJSONFromUrl("http://somesite.com/api/find?"+"somevar="+someJavaStringVar);
JSONObject json = new JSONObject(jsonString)
JSONObject json_event = json.getJSONObject("event");
JSONArray json_array_participants = json_event.getJSONArray("participants");
You can iterate through the array like any other array to get subobjects or whatever:
for(int i=0; i < json_array_participants.getLength(); i++) {
JSONObject participant = json_array_participants.getJSONObject(i);
// Do stuff
}
As a side note - I WOULDN'T use GSON until you understand the underlying protocol, at least a little - because you never know when you might want to parse your JSON from a different language for some reason.
I would strongly recommend to use gson instead as your preferred parser since it will do all the job of serializing and deserializing for you except creating the domain objects.
This tutorial should get you going:
http://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html
This will depend on what the server is supposed to return. It could be an array of anything and if this is a public service, there should be a specification to go off of.
If you are in charge of the server portion as well, and you have a backing object, Google's GSON library is extremely easy to use. It will also keep type information straight.

Categories

Resources