can't parse JSON File - android

I'm trying to Parse this JSON-File but I get an error which I understand but don't know how to find a way around it
JSONArray locations = new JSONArray(jsonString);
Error
Json parsing error: Value [{"lon":8.6520691,"type":"fuel","address":"Frankfurter Straße 65","lat":49.8848387,"name":"Esso"},{
.."lon":8.6419863,"type":"fuel","address":"Rüdesheimer Straße 114","lat":49.8540121,"name":"Aral Tankstelle"},{"lon":8.6468131,"type":"fuel","address":"Heidelberger Straße 55-59","lat":49.8614199,"name":"Total"},{"lon":8.6311635,"type":"fuel","address":"Pallaswiesenviertel Pallaswiesenstraße","lat":49.8847555,"name":"Firma Karaahmetaglu"},{"lon":8.6429677,"type":"fuel","address":"Pallaswiesenstraße 85","lat":49.8825735,"name":"Shell"},{"lon":8.6443997,"type":"fuel","address":"Johannesviertel Kasinostraße","lat":49.8796515,"name":"Jet"},{"capacity":90,"lon":8.647085,"type":"pub","address":"Mollerstadt Saalbaustraße","lat":49.8714409,"name":"Unikum"}] of type org.json.JSONArray cannot be converted to JSONObject
Changed
if(c.has("icon"){
icon = c.getString("icon");
}else{
icon = "";
}
To
if(c.has("icon"){
icon = c.getString("icon");
}else{
icon = "#drawable/seekbarthumb1";
}
SOLVED

The root-object of a json-file should be an json-object, you can make a tag with the list named "data". Some parsers may allow it but it is not recommended. If you cannot change the file, just parse "{ \"file\": " + jsonStr + "}" and use its member file.
Edit:
An array as root-object should be supported (you are writing the code, as the root-object is not an array (JSONArray) but an object (JSONObject), but it is an array), strings or numbers are not always supported.
Just change the type parsing the string:
JSONObject jsonObject = new JSONObject(jsonStr);
JSONArray locations = jsonObject.getJSONArray("");
to
JSONArray locations = new JSONArray(jsonStr);
The error occurs in the first line and is yielded by the parser because it expects an object and not an array.

Related

How to use single word as JSON data in android?

I am trying to extract the JSON data which is just a single word. I have used JSON Array when it was a long list of a set of data but this time it just a word like - done or failed.
My Code is -
JSONObject jsonObject = new JSONObject(s);
//JSONArray jsonArray = jsonObject.getJSONArray("contacted");
loggingTest = jsonObject.getString("??"); // what to put here (??) as
//there is just a single word.
It may be very easy to get it but I feels I am missing something. Thanks for your help in advance.
URL just gives a word like - done that's it not even " or : { nothing
Then simply use the String variable s , don't convert it into json
plus you can put this JSONObject jsonObject = new JSONObject(s); in try-catch to recognize that respose is simply a valid json or not , if not it will throw an exception
try{
// exception will be thrown in case of invalid json
JSONObject jsonObject = new JSONObject(s);
}
catch(JSONException e){
// s containing a single word so use it as it is
}

unterminated character when parsing json in android

I am using the Retrofit package from square to make http request to my server. I get json data from my server that needs to be parsed. The problem I'm having is when the name field has more than one word I get a "Unterminated object at character". What can be the problem.
This works fine
{results=[{id=23.0, name= Canada}]}
This does not
{results=[{id=23.0, name= United States}]}
JSONObject jsonResponse = new JSONObject(data);
JSONArray result = jsonResponse.getJSONArray("results");
for(int i=0; i <result.length();i++ )
{
MyObj obj = new MyObj();
obj.id= result.getJSONObject(i).optString("id").toString();
obj.name=result.getJSONObject(i).optString("name").toString();
p.add(obj);
}
Your input is not valid according to the JSON specs.
It shoud be:
{"results":[{"id":23.0, "name":"United States"}]}
See: http://json.org/

How parse json object and json array together

i have two situation of Json output .
one is data that found and i have a json array and a json object like this:
{"data":"yes"}[{"id":"10","number":"7","text":"text7","desc":"text7_again","user_code":"0"},{"id":"11","number":"8","text":"text8","desc":"text8_again","user_code":"1"}]
other situation is that data not found :
{"data":"no"}
just one json object.
how parse this data in android client for support two situtaion?
First, you should validate your json in http://jsonlint.com/ if you test it you will look that is a wrong json. So, for make it right, in your server your response should look something like this:
{"data":"yes","response":[{"id":"10","number":"7","text":"text7","desc":"text7_again","user_code":"0"},{"id":"11","number":"8","text":"text8","desc":"text8_again","user_code":"1"}]}
And in that case, in android
JSONObject jsonObj = new JSONObject(response);
if (jsonObj.getString("data").compareTo("yes") == 0) {
JSONArray jsonArray = jsonObj.getJSONArray("response");
//To-Do another code
}
and that's all
Here is a possible case: (you need to fix your json format)
Success -
string resultJSON =
{"success":true,
"data":[
{"id":"10","number":"7","text":"text7","desc":"text7_again","user_code":"0"},
{"id":"11","number":"8","text":"text8","desc":"text8_again","user_code":"1"}]}
Failed -
string resultJSON =
{"success":false}
Then
JSONObject jsonRoot = new JSONObject(resultJSON);
bool isSuccess = jsonRoot.getBoolean("success");
if (isSuccess) {
// do the array parser
for(int i=0; i<jsonData.lenght;i++) {
JSONObject jsonObj = jsonData.getJSONObject(i);
String id = jsonObj.getString("id"); // get the value of id
String desc = jsonObj.getString("desc"); // and so on...
}
}

JSON Error Value free at 6 of type java.lang.String cannot be converted to JSONObject

I don't see what's wrong with my JSON, I'm getting the error that it cannot be converted to JSONObject. I searched on the forum but I can't find the answer.
Code (to parse):
JSONObject json = new JSONObject(result.toString().replace("\\", " "));
JSONArray jArray = json.getJSONArray("timetable");
for(int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
String class_school = json_data.getString("class");
String teacher = json_data.getString("teacher");
String subject = json_data.getString("subject");
String room = json_data.getString("room");
timetList.add(new TimeTable(subject, class_school + " " + teacher + " " + " " + room));
}
JSON:
{"timetable":[{"teacher":"Woh","subject":"BVH","room":"017","change":"no"},{"teacher":"Rrl","subject":"BI","room":"045","change":"no"},{"teacher":"Ajg","subject":"WI","room":"019","change":"no"},{"teacher":"Sgh","subject":"NE","room":"119","change":"no"},{"teacher":"Rom","subject":"FA","room":"116","change":"no"},{"teacher":"Her","subject":"GS","room":"127","change":"no"},"free","free"]}
Logcat:
03-29 15:06:11.356: E/error(822): Value free at 6 of type java.lang.String cannot be converted to JSONObject
Seems to me, you're trying to parse last two entries ("free","free") to a JSONObject. If for some reason you need to add empty entries use {}.
Consider using optString instead of getString (or use try catch statment to handle exception)
Problem is in String. Your JSON String is broken and it is reason of
Value free at 6 of type java.lang.String cannot be converted to
JSONObject
Look at your String:
{
"timetable": [
{"teacher":"Woh","subject":"BVH","room":"017","change":"no"},
{"teacher":"Rrl","subject":"BI","room":"045","change":"no"},
{"teacher":"Ajg","subject":"WI","room":"019","change":"no"},
{"teacher":"Sgh","subject":"NE","room":"119","change":"no"},
{"teacher":"Rom","subject":"FA","room":"116","change":"no"},
{"teacher":"Her","subject":"GS","room":"127","change":"no"},
"free","free"
]
}
You need to remove this unexpected sequence:
"free","free"
and last comma in JSONObject with teacher's value Her and it should work.
Your string is valid JSON; however
JSONObject json_data = jArray.getJSONObject(i);
assumes that the entity at array position i be a JSON object. "free" is a string, which is not an object type in JSON (not surrounded by {}), getJSONObject(i) throws this exception when you try to make an object out of a string.
The strings can be extracted with jArray.getString(i), but the real trick is determining the type of the entity at position i. You can try a generic jArray.get(i) and then introspect the returned value to determine its type.

JSON Traversing to element using Json webservices in android

I am taking result of a json webservice in JSONObject. While printing this jsonObject it is printing exact result. I got problem at the time of fetching values in this result because i am reading a complex response that is in the form of
{"FoodMenuRS"
:{"Status":"Success",
"TotalResults":2,
"Results":{"Items":
{"Item":[
{"#Id":"6","#Name":"Tea"},
{"#Id":"4","#Name":"Coffee"}
]}}}}
Here i am reading through,
JSONArray jsonArray = json.getJSONArray("Item");
Here i am getting error "No Value for Item"
Where as i got fetched value while calling another service which is simple in format,
{"earthquakes":
[{"eqid":"c0001xgp","magnitude":8.8,"lng":142.369,"src":"us","datetime":"2011-03-11 04:46:23","depth":24.4,"lat":38.322},
{"eqid":"2010xkbv","magnitude":7.5,"lng":91.9379,"src":"us","datetime":"2010-06-12 17:26:50","depth":35,"lat":7.7477}]}
I called it using,
JSONArray earthquakes = json.getJSONArray("earthquakes");
Please help how to fetch this type of Json response. Thanks in advance.
ya it is very complex but i refer you to use Gson library to parse Json as it is parse in structural manner example
check this:
http://www.androidcompetencycenter.com/2009/10/json-parsing-in-android/
Done with
JSONObject menuObject = jObject.getJSONObject("menu");
String attributeValue = menuObject.getString("value");
private String jString = "{\"menu\": {\"id\": \"file\", \"value\": \"File\", \"popup\": { \"menuitem\": [ {\"value\": \"New\", \"onclick\": \"CreateNewDoc()\"}, {\"value\": \"Open\", \"onclick\": \"OpenDoc()\"}, {\"value\": \"Close\", \"onclick\": \"CloseDoc()\"}]}}}";
JSONObject menuObject = jObject.getJSONObject("menu");
String attributeId = menuObject.getString("id");
String attributeValue = menuObject.getString("value");
JSONObject popupObject = menuObject.getJSONObject("popup");
JSONArray menuitemArray = popupObject.getJSONArray("menuitem");
With every new curley braces call getJSONObjectand for child call getString.
Or you can follow Gson concept to fetch response.

Categories

Resources