Why double slashes front of JSON String - java

I have a JSON string from google, which i can not use it because of the double slashes in front of the JSON string, it returns JSON exception.
How can i escape them before parse?
https://www.google.com/finance/info?q=asels
// [ { "id": "530630671033488" ,"t" : "ASELS" ,"e" : "IST" ,"l" :
"13.72" ,"l_fix" : "13.72" ,"l_cur" : "TRY13.72" ,"s": "0"
,"ltt":"6:10PM GMT+3" ,"lt" : "Jan 20, 6:10PM GMT+3" ,"lt_dts" :
"2017-01-20T18:10:00Z" ,"c" : "+0.04" ,"c_fix" : "0.04" ,"cp" : "0.29"
,"cp_fix" : "0.29" ,"ccol" : "chg" ,"pcls_fix" : "13.68" } ]

You need to remove the two double slashes in beginning, then you have a regular JSON String that you can parse.
You can do it like this:
String yourJsonStringFromGoogle = ...
fixedJsonString = yourJsonStringFromGoogle.substring(2);
Here, substring(n) removes n letters from the beginning of the string.

Related

Escape rogue backslashes in a string

I have a JSON string like this in the database:
{"name" : "DROCK", "details" : [{"age" : "23", "degree" : "BE", "Experience" : "worked in a company\6as an intern"}]}
I want to remove \ character but which is not a valid escape string. I tried using StringEscapeUtil but it is not helping me out here.
The code I've used here:
import org.apache.commons.lang.xwork.StringEscapeUtils;
public class JSONEscape {
public static void main(String args[]) {
String testString = "{\"name\" : \"DROCK\", \"details\" : [{\"age\" : \"23\", \"degree\" : \"BE\", \"Experience\" : \"worked in a company\6as an intern\"}]}";
System.out.println(StringEscapeUtils.escapeJava(testString));
}
}
How should I escape valid \ characters and remove rogue characters like this. but I would like to retain the valid escape characters like \n, \t,etc.
Finally i would like a result like this:
{"name" : "DROCK", "details" : [{"age" : "23", "degree" : "BE", "Experience" : "worked in a company6as an intern"}]}
If you want to remove bad escape sequences in a JSON string, then that's easy.
String testString = "{\"name\" : \"DROCK\", \"details\" : [\"age\" : \"23\", \"degree\" : \"BE\", \"Experience\" : \"worked in a company\\6as an intern\"]}";
System.out.println(testString.replaceAll("\\([^bfnrt\"\\])", "$1"));
That RegEx literally just means "wherever a backslash is followed by an invalid escape character, drop the backslash".

Error in Creating JSON object

I'm getting an JSON array as a string value and I need to create a JSON object using that. array code is like this.
{"eventsList" : [
"requestId" : "82334-adf86d-8bac8ef-289c"
events:[
{
"eventType" : "receiveLocation_Event",
"externalId" : "973af2f8-820b-457b-89c2",
"description" : "Test Event",
"whenOccurred" : "06-Aug-2013 07.15.01.0 AM",
"partnerId" : "cecdbd94-ac60-4db0-b7f2",
"tagsAndValues" : {
"locationAccuracy" : "10",
"attr2" : "value2"
},
"count" : "2"
},
{
"eventType" : "SEND_SMS_sendSmsEvent",
"externalId" : "45af4f8-87-4f42b-832abc",
"description" : "Another Test Event",
"whenOccurred" : "06-Aug-2013 08.16.01.0 AM",
"partnerId" : "cecdbd94-ac60-4db0-b7f2",
"tagsAndValues" : {
"messageLength" : "135",
"attrX" : "valueX"
},
"count" : "1"
}
]
}
]
}
i try to create an JSON object using folowing code line
SONObject jsonObject = new JSONObject(string);
I'm getting an error when i run this.
org.json.JSONException: Expected a ',' or ']' at character 35
at org.json.JSONTokener.syntaxError(JSONTokener.java:413)
at org.json.JSONArray.<init>(JSONArray.java:143)
at org.json.JSONTokener.nextValue(JSONTokener.java:351)
at org.json.JSONObject.<init>(JSONObject.java:206)
at org.json.JSONObject.<init>(JSONObject.java:420)
Please help me to solve this issue.
There are several mistakes.
After [ a list of comma-separated values is expected, but you have a colon after "requestId". You probably meant for the [ on line 1 to be a {.
Given the last issue, you probably want a comma after "82334-adf86d-8bac8ef-289c"
If you drop your text into an online JSON formatter and validator, such as this one it will point out all your errors.
Problem is here:
...
"requestId" : "82334-adf86d-8bac8ef-289c"
events:...
You forgot some punctuation:
...
"requestId" : "82334-adf86d-8bac8ef-289c",
"events":......
Use this instead this is JSON syntax. All keys are strings.
This is how the String should be;
{"eventsList" : [
{"requestId" : "82334-adf86d-8bac8ef-289c"},
{ "events":[
{
"eventType" : "receiveLocation_Event",
"externalId" : "973af2f8-820b-457b-89c2",
"description" : "Test Event",
"whenOccurred" : "06-Aug-2013 07.15.01.0 AM",
"partnerId" : "cecdbd94-ac60-4db0-b7f2",
"tagsAndValues" : {
"locationAccuracy" : "10",
"attr2" : "value2"
},
"count" : "2"
},
{
"eventType" : "SEND_SMS_sendSmsEvent",
"externalId" : "45af4f8-87-4f42b-832abc",
"description" : "Another Test Event",
"whenOccurred" : "06-Aug-2013 08.16.01.0 AM",
"partnerId" : "cecdbd94-ac60-4db0-b7f2",
"tagsAndValues" : {
"messageLength" : "135",
"attrX" : "valueX"
},
"count" : "1"
}
]
}
]
}
the requestId and event must be like this: {"requestId" : "82334-adf86d-8bac8ef-289c"},
{ "events":
And also there must be closing } after closing the inner JSONArray ]

Parsing JSON files using org.json [duplicate]

This question already has answers here:
How to parse JSON in Java
(36 answers)
Closed 5 years ago.
How do i parse a JSON that is like this?
[{
"id" : 28010942,
"type" : "trafficlight",
"title" : "225 - Shaw Blvd. / Gomezville - Flashing",
"activeFrom" : "Apr 30, 2013 6:18:00 PM",
"publiclyVisible" : true,
"locationLat" : 14.589366803498653,
"locationLon" : 121.03713870048522,
"publicDescription" : ""
}, {
"id" : 28010939,
"type" : "trafficlight",
"title" : "301 - Andalucia (A. Mendoza) / P. Campa - No Display",
"activeFrom" : "Apr 30, 2013 6:00:00 PM",
"publiclyVisible" : true,
"locationLat" : 14.608034456366056,
"locationLon" : 120.98599433898926,
"publicDescription" : ""
} ...
]
I can parse ones that have an object and jsonArrays but this one has neither. How can i iterate through these and be able to store each information like the "id". I'm using the org.json library, or should i use a different one?
If you need to parse try the below
[ // json array node
{ // json object node
"id": 28010942,
"type": "trafficlight",
To parse
JSONArray jarray = new JSONArray("Myjsonstring");
for(int i=0 ;i<jarray.length();i++)
{
JSONObject jb = (JSONObject)jarray.get(i);
String id = jb.getString("id");
String type = jb.getString("type");
// same for others title, activeform..
}

Trying to parse JSON to String in Java

I'm trying to parse this stock info at:
http://www.google.com/finance/info?client=ig&q=csco
that's in JSON format to a map, essentially following this tutorial I saw using the quick-json jar but it keeps giving me an exception and I can't figure out why. Here's the code, any help is greatly appreciated
Tutorial link: https://code.google.com/p/quick-json/
public static void main(String args[]) throws IOException
{
String value="";
URL uri = new URL("http://www.google.com/finance/info?client=ig&q=csco");
BufferedReader input = new BufferedReader(new InputStreamReader(uri.openStream(), "UTF-8"));
while(input.readLine()!=null)
{
value+=input.readLine();
}
JsonParserFactory factory = JsonParserFactory.getInstance();
JSONParser parse = factory.newJsonParser();
Map jsonData =parse.parseJson(value);
System.out.println((String)jsonData.get("e"));
}
Here's the exception I get:
Exception in thread "main" com.json.exceptions.JSONParsingException: #Key-Heirarchy::root[0]/ #Key:: COMMA or ] is expected. but found :...#Position::5
at com.json.utils.JSONUtility.handleFailure(JSONUtility.java:124)
at com.json.parsers.JSONParser.stringLiteralTemplate(JSONParser.java:574)
at com.json.parsers.JSONParser.nonValidatingValueTemplate(JSONParser.java:698)
at com.json.parsers.JSONParser.jsonArrayTemplate(JSONParser.java:454)
at com.json.parsers.JSONParser.parseJson(JSONParser.java:170)
at parser.Scratch.main(Scratch.java:27)
EDIT: I also tried Map jsonData =parse.parseJson(value.substring(3) to start at [ but it still gives me an error
In addition to removing the leading // fix your loop as well. Change
while(input.readLine()!=null) // skipping odd lines
{
value+=input.readLine(); // reading even lines
}
to
String line = null;
while((line = input.readLine()) !=null)
{
value +=line;
}
or, better use a StringBuilder like
String line = null;
StringBuilder json = new StringBuilder();
while((line = input.readLine()) !=null)
{
json.append(line);
}
value = json.substring(3); // removes the leading "// "
EDIT:
I'm not familiar with your JSON parser. With the org.json. Java parser you could do it this way.
JSONArray jsonRoot = new JSONArray(value);
JSONObject quote = jsonRoot.get(0);
System.out.println ("e = " + quote.getString("e"));
But, as a workaround you could strip the [] from StringBuilder as
// removes the leading "// [" and trailing "]"
value = json.substring(4, json.length() - 1);
This json is not a valid, have two "//".
Use http://jsonlint.com/ to validate this
The response from that URL starts with //, which isn't valid JSON:
// [ { "id": "99624" ,"t" : "CSCO" ,"e" : "NASDAQ" ,"l" : "24.00" ,"l_cur" : "24.00" ,"s": "2" ,"ltt":"4:00PM EDT" ,"lt" : "Jun 25, 4:00PM EDT" ,"c" : "-0.05" ,"cp" : "-0.21" ,"ccol" : "chr" ,"el": "24.00" ,"el_cur": "24.00" ,"elt" : "Jun 25, 5:54PM EDT" ,"ec" : "0.00" ,"ecp" : "0.00" ,"eccol" : "chb" ,"div" : "0.17" ,"yld" : "2.83" } ]
According to this and this, the Google Finance API is deprecated anyway, so you may want to find something else.
Following blog has enough number of very good examples on quick-json parser
It has got other competitive parsers examples as well
http://codesnippets4all.com/html/parsers/json/quick-json.htm
Add this to your code:
String line = null;
while((line = input.readLine()) !=null)
{
value += line;
}
value = value.replace("// ", "");
You need to replace the // at the beginning to "clean" the JSON before you can parse it.
It seems you are using old quick-json parser version. Use the latest version for parsing
quick-json-1.0.2.3.jar
I could see that the json is coming as follows,
// [
{
"id": "99624"
,"t" : "CSCO"
,"e" : "NASDAQ"
,"l" : "25.41"
,"l_cur" : "25.41"
,"s": "2"
,"ltt":"3:59PM EDT"
,"lt" : "Jul 10, 3:59PM EDT"
,"c" : "+0.25"
,"cp" : "1.01"
,"ccol" : "chg"
,"el": "25.55"
,"el_cur": "25.55"
,"elt" : "Jul 10, 7:07PM EDT"
,"ec" : "+0.14"
,"ecp" : "0.55"
,"eccol" : "chg"
,"div" : "0.17"
,"yld" : "2.68"
}
]
This is not valid JSON, it should not be preceded by //
// [
remove // and just use from [ till end of the json string
i was able to parse successfully the below json string without //
[
{
"id": "99624"
,"t" : "CSCO"
,"e" : "NASDAQ"
,"l" : "25.41"
,"l_cur" : "25.41"
,"s": "2"
,"ltt":"3:59PM EDT"
,"lt" : "Jul 10, 3:59PM EDT"
,"c" : "+0.25"
,"cp" : "1.01"
,"ccol" : "chg"
,"el": "25.55"
,"el_cur": "25.55"
,"elt" : "Jul 10, 7:07PM EDT"
,"ec" : "+0.14"
,"ecp" : "0.55"
,"eccol" : "chg"
,"div" : "0.17"
,"yld" : "2.68"
}
]
Below is the output i've got with version quick-json-1.0.2.3.jar
{root=[{e=NASDAQ, c=+0.25, div=0.17, l=25.41, lt=Jul 10, 3:59PM EDT, ec=+0.14, ltt=3:59PM EDT, elt=Jul 10, 7:07PM EDT, id=99624, yld=2.68, el_cur=25.55, t=CSCO, cp=1.01, s=2, el=25.55, l_cur=25.41, eccol=chg, ccol=chg, ecp=0.55}]}

java.lang.String cannot be converted to JSONObject

In my android application,i calling one webservice and it is returning one jsonobject.In device i getting one response like this..
"{ \"Time_Stamp\" : \"10/10/2012 4:26 PM\", \"records\" : [ { \"'Name'\" : \"'LD-00000002'\", \"'Appointment_Date_Time'\" : \"'null'\", \"'Phone'\" : \"'9909955555'\", \"'Home_Country_Address'\" : \"'null'\", \"'Occupation'\" : \"'null'\", \"'SR_Appointment_Status'\" : \"'Open'\", \"'Id'\" : \"'a0OE0000001iLynMAE'\", \"'SR_Appointment_Comment'\" : \"'testing'\", \"'ProductsOfInterest'\" : \"'null'\", \"'ActivityName'\" : \"'Sales'\", \"documentsList\" : [ ] }, { \"'Name'\" : \"'LD-00000002'\", \"'Appointment_Date_Time'\" : \"'null'\", \"'Phone'\" : \"'9909955555'\", \"'Home_Country_Address'\" : \"'null'\", \"'Occupation'\" : \"'null'\", \"'SR_Appointment_Status'\" : \"'Open'\", \"'Id'\" : \"'a0OE0000001iLynMAE'\", \"'SR_Appointment_Comment'\" : \"'testing'\", \"'ProductsOfInterest'\" : \"'null'\", \"'ActivityName'\" : \"'Sales'\", \"documentsList\" : [ { \"numberOfImages\" : 3, \"Name\" : \"new document\", \"Mandatory\" : false, \"FilePath\" : null, \"Category\" : null } ] } ]}"
i trying convert it into an object like this
JSONObject jsonObj=new JSONObject(objMngr.getResponse());
when converting it throwing one exception "java.lang.String cannot be converted to JSONObject"...below is the exact exception that it is throwig ..What is the reason and how can i solve this issue??
{ "Time_Stamp" : "10/10/2012 4:26 PM", "records" : [ { "'Name'" : "'LD-00000002'", "'Appointment_Date_Time'" : "'null'", "'Phone'" : "'9909955555'", "'Home_Country_Address'" : "'null'", "'Occupation'" : "'null'", "'SR_Appointment_Status'" : "'Open'", "'Id'" : "'a0OE0000001iLynMAE'", "'SR_Appointment_Comment'" : "'testing'", "'ProductsOfInterest'" : "'null'", "'ActivityName'" : "'Sales'", "documentsList" : [ ] }, { "'Name'" : "'LD-00000002'", "'Appointment_Date_Time'" : "'null'", "'Phone'" : "'9909955555'", "'Home_Country_Address'" : "'null'", "'Occupation'" : "'null'", "'SR_Appointment_Status'" : "'Open'", "'Id'" : "'a0OE0000001iLynMAE'", "'SR_Appointment_Comment'" : "'testing'", "'ProductsOfInterest'" : "'null'", "'ActivityName'" : "'Sales'", "documentsList" : [ { "numberOfImages" : 3, "Name" : "new document", "Mandatory" : false, "FilePath" : null, "Category" : null } ] } ]} of type java.lang.String cannot be converted to JSONObject
try
JSONObject jsonObj=new JSONObject(objMngr.getResponse().toString().replace("\\", " "));
Your jsonString seems allright. However your response type may not be string. Try it.
The problem is with already escaped inverted commas sent by the server.
First convert your response to a String then try to create a JSONObject
I think, getResponse() is already string but response isn't valid JSON.If response isn't string,you can convert string with toString() method.
It seem there are some hidden characters on your string.
Try this
return new JSONObject(json.substring(json.indexOf("{"), json.lastIndexOf("}") + 1));
Seems like you have dumped object to JSON string twice on server-side.
object --dumps()--> json string --dumps()-> one string in json
So you should remove the second dumping.
Otherwise you can unescape your string this way How to unescape a Java string literal in Java?.
The first way is better and easier i think.

Categories

Resources