org.json.JSONException: Expected literal value at character 550 of - android

I am trying to read JSON file from asset folder. But I get the following exception
org.json.JSONException: Expected literal value at character 550
I searched lot of stuff but didn't find anything relative. Here is my JSON file.
I find JSON object on 550 is "names": ["Santosh","Sandip","Arvind"],. I am trying to solve it but don't know what happens in my code.
Here is my code.
I also debug my code but when control goes on JSONObject jsonObject = new JSONObject(text); it throw exception and goes in first catch block.
Please give me any reference or hint to solve this problem.
Any help appreciated.

your JSON is invalid.your JSON should look like this
{
"resultCount": 3,
"SearchedTerm": "Wada Pav",
"results": [
{
"locationname": "Mahableshwar Hotel",
"locationid": "12345",
"locationaddress": "baner, Pune",
"dishrating": "4",
"dishname": "Wada Pav",
"dishid": "234",
"dishcategory": "Snacks",
"dishnotes": "Spicy Wada Pav",
"dishpreviewurl": "http://xxx.yyy.zzz/mahableshwar/1.jpg",
"dishtotalvotes": "9999",
"friendslistvoted": {
"friendscount": "3",
"names": [
"Santosh",
"Sandip",
"Arvind"
]
},
"dishimageurl": "http://xxx.yyy.zzz/mahableshwar/2.jpg",
"mylastrating": "4"
}
]
}
try using a JSON validator before using it (like JSLint).

I'm using following to get standard JSON format.
This one is better.
public static String convertStandardJSONString(String data_json) {
data_json = data_json.replaceAll("\\\\r\\\\n", "");
data_json = data_json.replace("\"{", "{");
data_json = data_json.replace("}\",", "},");
data_json = data_json.replace("}\"", "}");
return data_json;
}

I use jsoneditoronline online tool that works pretty good.

this works for me
public static String convertJSONString(String data) {
data = data.replace("\\", "");
return data; }

Related

How to create JSON object in flutter?

I'm working on one application in which I want to fill the registration form and pass this data to API.I tried almost all solutions but not solved this issue.
I'm getting this type of data after filling the form
[
{Date of Birth of the Baby: 08/01/1997},
{Gender of the baby: male},
{Time of Birth of the Baby: 12.00 pm},
{Father's Name: Nnn},
{Mother's Name: Hbhh},
{Any Extra Details?: Bnn}
]
and I want this type of data
{
"Date of Birth of the Baby": "08/01/1997",
"Gender of the baby": "male",
"Time of Birth of the Baby": "12.00 pm",
"Father's Name": "Nnn",
"Mother's Name": "Hbhh",
"Any Extra Details?": "Bnn"
}
var fieldsData = [];
final myControllers = [];
mydynamicData() {
for (var i = 0; i <= widget.fieldData.length; i++) {
fieldsData.add({
widget.fieldData[i]['question'],
myControllers[i].text != null || myControllers[i].text != ""
? myControllers[i].text
: ""
});
}
print("fieldsData:${fieldsData}");
}
This is my method i know this issue occurred due to for loop but without for loop I'm not getting all fields data. so please help.
Import:
import 'dart:convert';
then you can use:
json.encode(fieldsData);
As you have a list of objects, it may be necessary to make a for in the list calling json.encode for each item, then encoding the result.

Parse JSON with optional field

I'm trying to parse in android studio a JSON, that containts this :
"stops":
[
{
"num": 1,
"time": "2016-04-27T06:15:00.000Z",
"title":"Flight to London",
"desc":"Barcelona BCN-London-Gatwick LGW",
"type":"0",
"subtype":0
},
{
"num": 2,
"time": "2016-04-27T10:35:00.000Z",
"title":"Gatwick express",
"desc":"From Airport to London",
"type":"0",
"subtype":1
},
{
"num": 3,
"time": "2016-04-27T12:15:00.000Z",
"title":"Pub the black horse",
"desc":"From Airport to London",
"type":1,
"subtype":1,
"location": "51.476334, -0.062700",
"images": [ "https://fitzrovianews.files.wordpress.com/2011/01/black_horse_rathbone_pl.jpg"
]
},
{
"num": 4,
"time": "2016-04-27T12:16:47.000Z",
"title":"The Tower Bridge",
"desc":"# The Tower Bridge Facts\n## Architecture\n**Tower Bridge** is a combined bascule and suspension bridge in London built in _1886–1894_. The bridge crosses the River Thames close to the Tower of London and has become an iconic symbol of London. Tower Bridge is one of five London bridges now owned and maintained by the Bridge House Estates, a charitable trust overseen by the City of London Corporation. \n>It is the only one of the Trust's bridges not to connect the City of London directly to the Southwark bank, as its northern landfall is in Tower Hamlets.\n## The bridge Exhibition\nThis must-see London attraction invites you to step inside the most famous bridge in the world to explore its iconic structure, spectacular views and glass floor, modern exhibitions and magnificent Victorian Engine Rooms! ",
"type":1,
"subtype":6,
"location": "51.507792, -0.087786",
"images": [
"https://i.ytimg.com/vi/nby0Mr2LfBQ/hqdefault.jpg",
"http://raindropsofsapphire.com/wp-content/uploads/2011/10/london-bridge.jpg",
"http://www.londonforfree.net/gizmo/wp-content/uploads/2015/02/southwark-bridge.jpg"
]
},
{
"num": 5,
"time": "2016-04-27T12:18:10.000Z",
"title":"St. Paul Cathedral",
"desc":"# HISTORY \nSt **Paul's Cathedral**, London, is an _Anglican cathedral_, the seat of the _Bishop of London_ and the mother church of the Diocese of London. \n * It sits on Ludgate Hill at the highest point of the City of London and is a Grade 1 listed building. \n * Its dedication to Paul the Apostle dates back to the original church on this site, founded in AD 604.",
"type":1,
"subtype":6,
"location": "51.513825, -0.098351",
"images": [
"https://d1wgio6yfhqlw1.cloudfront.net/sysimages/product/resized6/Interior_St_Pauls_Cathedral_132_12992.jpg",
"https://d1kioxk2jrdjp.cloudfront.net/resized/486x324/48-st_pauls_ctahedral_millenirm_bridge.jpg",
"http://i4.mirror.co.uk/incoming/article8299330.ece/ALTERNATES/s615b/LOND-2016-052-HMQ-St-Pauls-Thanks-Giving-704JPG.jpg"
]
}
]
The problem is, i don't know how to deal with the field "location" or "images" which are optional. I know how to deal with the first "stop", i'm doing this :
JSONArray stops = jsonObj.getJSONArray("stops");
for (int i = 0; i < stops.length(); i++) {
JSONObject c = stops.getJSONObject(i);
String num = c.getString("num");
String time = c.getString("time");
String title = c.getString("title");
String descripcion = c.getString("desc");
String type = c.getString("type");
String subtype = c.getString("subtype");
......
}
But i don't know how to check it here is a elment location or a jsonArray "images"...
best way to handle optional fields in JSON is to use opt instead of get
opt provides the parsed value if exist or default value for that datatype if requested key does not exist.
best thing is, it don't even need a try catch block since it always returns a value and in case of any error from server, it will not let your app crash or prevent other values from being parsed.
String location = response.optString("location");
if location exist in response, then it will initialize with the value or it will leave the string null. in case of int or long default is 0, in case of boolean default is false. read about opt for more details.
Use has() method
JSONArray stops = jsonObj.getJSONArray("stops");
for (int i = 0; i < stops.length(); i++) {
JSONObject c = stops.getJSONObject(i);
String num = c.getString("num");
String time = c.getString("time");
String title = c.getString("title");
String descripcion = c.getString("desc");
String type = c.getString("type");
String subtype = c.getString("subtype");
if(c.has("location") && !c.isNull("location")){
// parse location
}
if(c.has("images") && !c.isNull("images")){
// parse images
}
.....
}
you should use Retrofit and Google Gson, where you do not have to do lot of work,
they will do the job for you.
look at these
https://guides.codepath.com/android/Consuming-APIs-with-Retrofit
http://www.vogella.com/tutorials/Retrofit/article.html

How to Parse the following json response in Android?

The problem with the following JSON response parsing is that is giving the error as "Unterminated object at character 32".
{
"0": {
"review": {
"reviewTime": "2015-09-24 22:07:03",
"author": "John Doe",
"rating_5": 1.5,
"rating": 2
}
},
"1": {
"review": {
"reviewTime": "2015-09-25 18:05:14",
"author": "Samantha",
"rating_5": 5,
"timestamp": 1443184514,
"rating": 5
}
},
"count": 3,
"review_url": "https://localhost/reviews"
}
I'm validated your json using in http://jsonformatter.curiousconcept.com/ and it's valid.
The 32 character is a date and must be quoted. Check in debug mode if the date is quoted.
In one of your comments to your question you wrote that your response looks like:
{ count=2041.0, 4={review={reviewTime=2015-09-24 22:07:03, author=Neha Primith, rating_5=1.5, rating=2.0, reviewTimeFriendly=yesterday}}, 1={review={reviewTime=2015-09-24 22:07:03, author= John Doe, rating_5=1.5, rating=2.0,}}, 0={review={reviewTime=2015-09-25 18:05:14, author=Samantha, rating_5=5.0, rating=5.0}}, , review_url=https://localhost/reviews,count=2 }
But it's not json format. Json format is sensitive to quotes. So make sure you get a properly formatted response

json parsing without name in android

i have worked with json name value pair before works fine and great but below is my json object in which there is no name and only value. Can anyone tell is it possible to use this type of json in android if yes then how to extract values from this json object. or any related link will be great.
JSON OBJECT
{
"log_list": [
[
"21",
"doctorFisher",
"Pharmacy 1",
"patientfish",
"test",
"2014-08-25 05:58:18",
"record UCI tech FDNY icky shut rack soon sun TDK tell. ox it'll ohm URL did GCVO dash ugly dog did flood idiot fluff if if rid t-shirts didn't TechTV only chef doc scotch Rebekah an if lb tax scotch am ICN JCB JCB HGV JCB HGV in on pm tax UDC OK red uh HK ohm",
"<img id=\"prescription_image\" onClick=showPrescriptionDetails(\"3c59dc048e8850243be8079a5c74d079\") onmouseover=\"this.style.cursor='pointer'\" src=\"\" width=\"20\" height=\"20\">"
],
[
"20",
"doctortest12345",
"Pharmacy 1",
"testpatient12345",
"test",
"2014-08-25 03:57:32",
"she'd Urdu text scuff uno dad uno each ink why tough days ICO saved USCIS David rig though end FDIC UCI's for USCIS tend did for dog such vidi fly floor exited did DND hand bid GMD.",
"<img id=\"prescription_image\" onClick=showPrescriptionDetails(\"98f13708210194c475687be6106a3b84\") onmouseover=\"this.style.cursor='pointer'\" width=\"20\" height=\"20\">"
]
}
thanks in advance
Yes, that format would work and you can pretty easily use it.
Assuming you have a variable String json which contains that data:
JSONObject jsonObj = new JSONObject(json);
Now log_list would be parsed as a JSONArray like so:
JSONArray logJsonArray = jsonObj.getJSONArray("log_list");
Then you can iterate through that outer array very similar to how you would a normal array or ArrayList:
for(int outerArrayPos = 0; outerArrayPos < logJsonArray.length(); outerArrayPos++){
JSONArray innerArray = logJsonArray.getJSONArray(outerArrayPos);
for(int innerArrayPos = 0; innerArrayPos < innerArray.length(); innerArrayPos++){
String valueAtIndex = innerArray.getString(innerArrayPos); //innerArray
// Do whatever you want with the values here
}
}
That will parse your String, but figuring out how to actually use that data is going to be most of your struggle, so I hope the order in which the information is returned will always be the same for your sake.
If you can, I would definitely recommend using a JSONObject for the data that is currently contained in your inner array. e.g.
{
"log_list": [
{
"id": "21",
"name": "doctorFisher",
.....
}
]
}

JSON: Concatenate 2 string values in value

Hi I have a JSON like:
{
"name" : "avg",
"code" : {"value":" import android
droid = android.Android()
droid.makeToast('Hello, Android!')",
"type":"PythonScript"
}
}
However, in value field(Python script for Android) I need a newline character between the 3 statements. Something like,
"value":"import android " + "\n" + "droid = android.Android()" + "\n" + "droid.makeToast('Hello, Android!')"
Is it possible to do this? Thanks in advance :)
Its better to configure your server to send you HTML-encoded value string. Afterwards, it would be easier to re-construct and show in TextView, for e.g.
Your expected Json response:
{
"name": "avg",
"code": {
"value": "import android<br />droid = android.Android()<br />droid.makeToast('Hello, Android!')",
"type": "PythonScript"
}
}
Once you read the value string:
String html_encoded_string = "import android<br />droid = android.Android()
<br />droid.makeToast('Hello, Android!')";
Then its easier to put it in TextView using html encoding:
yourTextView.setText(Html.fromHtml(html_encoded_string));

Categories

Resources