parsing string to JSON - java

My console prints value of String result as
[{"series":[ {\"data\" : [ 100.0 , 222.0 , 555.0 , 367.0 , 100.0]}],"yAxis":{\"plotLines\":[{\"dashStyle\":\"solid\",\"color\":\"black\",\"width\":\" 2.0\",\"value\":\" 27.0\",\"label\":{\"text\":\"Average\"}}],\"title\":{\"text\":\"FTFR\"}},"title":{\"text\":\"First Time Fix Rate\"},"legend":{\"backgroundColor\":\"#FFFFFF\"},"chart":{\"type\":\"line\"},"xAxis":{\"title\":{\"text\":\"Time(Years)\"},\"categories\":\[2009 , 2010 , 2011 , 2012 , 2013]}}]"
I need to parse the String result as valid JSON
but the following code throws exception:
JSONParser parser = new JSONParser();
Object obj = parser.parse(result);
Exception:
org.jboss.resteasy.spi.UnhandledException: Unexpected character (\) at
position 14.
How can i parse this kind of string to proper JSON?

You cannot use backslashes before double quotes. This is not correct JSON.

You shouldn't have \". Are you pasting this result into an IDE and you then try to parse it? (Netbeans adds \ to any quotation marks which are within another set of quotation marks.
If on the other hand, this is exactly the type of string you are getting, you would need to do something like so:
String str = "[{\"series\":[ {\\\"data\\\" : [ 100.0 , 222.0 , 555.0 , 367.0 , 100.0]}],\"yAxis\":{\\\"plotLines\\\":[{\\\"dashStyle\\\":\\\"solid\\\",\\\"color\\\":\\\"black\\\",\\\"width\\\":\\\" 2.0\\\",\\\"value\\\":\\\" 27.0\\\",\\\"label\\\":{\\\"text\\\":\\\"Average\\\"}}],\\\"title\\\":{\\\"text\\\":\\\"FTFR\\\"}},\"title\":{\\\"text\\\":\\\"First Time Fix Rate\\\"},\"legend\":{\\\"backgroundColor\\\":\\\"#FFFFFF\\\"},\"chart\":{\\\"type\\\":\\\"line\\\"},\"xAxis\":{\\\"title\\\":{\\\"text\\\":\\\"Time(Years)\\\"},\\\"categories\\\":\\[2009 , 2010 , 2011 , 2012 , 2013]}}]\"";
System.out.println(str.replaceAll("\\\\\"", "\"").replaceAll("\\\\\\[","["));
Yields:
[{"series":[ {"data" : [ 100.0 , 222.0 , 555.0 , 367.0 , 100.0]}],"yAxis":{"plotLines":[{"dashStyle":"solid","color":"black","width":" 2.0","value":" 27.0","label":{"text":"Average"}}],"title":{"text":"FTFR"}},"title":{"text":"First Time Fix Rate"},"legend":{"backgroundColor":"#FFFFFF"},"chart":{"type":"line"},"xAxis":{"title":{"text":"Time(Years)"},"categories":[2009 , 2010 , 2011 , 2012 , 2013]}}]"
In your case you might want to do away with two of the slashes in each case, I had to make them so that I can execute it on my IDE.

You could do something like
Object obj = parser.parse(result.replace("\\", ""));
to remove all your \ but it looks like a terrible hack. (By the way replacing the sequence \" by " shouldn't be enough because there is also a \[ that should make a problem.)
How do you get that string in your console?
It seems that the escape characters are not even systematically present.

Agree with npinti You might be trying to use the backslash as the escape character but it should not be visible when you print it. So probably you might have escaped the escape character. It is bit funny when you say it like that..:)

Related

JSON parser exception is observed for on fly JSON

I created a JSON file on the fly by using some runtime data and stored as string as like below:
JSON:
{
"ticketDetails": "kindle tracking ticket: TICKET0900060
Iimpact statement: impacted due to year 2020 format handling issue,
depending on the Gateway,
user can be asked to
try with another instrument.
Timeline: 00: 00 SAP Internal Declines spiked to 300 +
05: 22 AM flintron reported DECLINED errors since 0: 00 PST.
As per TDO,flitron is not seeing clear metrics impact " }
Note: I just copied the exact json which i'm getting at runtime. It containse \n space and exactly like above.
I can see few JSONObjects like ticketDetails is having huge description and when I tried to parse the above string is leading to parse error.
I tried the below way to eliminate the parse error by using
String removeSpecialCharacterFromJson= jsonString.replaceAll("[^A-Za-z0-9]","")
System.out.println(removeSpecialCharacterFromJson);
Sample Output:
kindletrackingticketTICKET0900060Iimpactstatementimpactedduetoyear2020formathandlingissue....[space between characters are removed and It's hard to read the string]
The above code removed all the special characters from the string and It will be successfully parsed. But the description is not having the space and It very hard to read the content after the above changes done.
I tried to escape the \s in the regular expression which is giving the original String value which is leading to parse exception.
String removeSpecialCharacterFromJson= jsonString.replaceAll("[^A-Za-z0-9\\s]","")
Is there anyohter way to handle this ? I just want to the ticketDetails to be readable format and It should not have any special characters and \n lines.
Can someone help me on this?
s in regular expression is not for space but for the whitespace
I guess that you may have some additional non allowed whitespace in your JSON string
Take a look at The JSON spec (RFC 7159):
Insignificant whitespace is allowed before or after any of the six structural characters.
ws = *(
%x20 / ; Space
%x09 / ; Horizontal tab
%x0A / ; Line feed or New line
%x0D ) ; Carriage return
Verify your values and look for improper whitespaces

Trying to create a regexp

I have a string which I want a string to parse via Java or Python regexp:
something (\var1 \var2 \var3 $var4 #var5 $var6 *fdsfdsfd #uytuytuyt fdsgfdgfdgf aaabbccc)
The number of var is unknown. Their exact names are unknown. Their names may or may not start with "\" or "$", "*", "#" or "#" and there're delimited by whitespace.
I'd like to parse them separately, that is, in capture groups, if possible. How can I do that? The output I want is a list of:
[\var1 , \var2 , \var3 , $var4 , #var5 , $var6 , *fdsfdsfd , #uytuytuyt , fdsgfdgfdgf , aaabbccc]
I don't need the java or python code, I just need the regexp. My incomplete one is:
something\s\(.+\)
something\s\((.+)\)
In this regex you are capturing the string containing all the variables. split it based on whitespace since you are sure that they are delimited by whitespace.
m = re.search('something\s\((.+)\)', input_string)
if m:
list_of_vars = m.group(1).split()

Matching words starting with a hash(#) sign

I am trying to extract words from a line which starts with a hash(#) symbol.
Suppose the line is :
#This #is#the line #containing multiple #tags.
The regex which I am using is :
(?:^|\s)(#\w+)
The answer which I'm getting is :
#This , #is , #containing , #tags
The output should be
#This , #is#the , #containing , #tags.
Please help.
Thanks
# is a non-word character. As such, the output that you get is expected.
Instead of looking for word characters match anything that is not a space.
(?:^|\s)(#[^ ]+)

Java replace all invalid character for regex

My String is huge and it will keep changing as I read each String in a loop. It can contain any characters like " , / , \ . $ ,? , [ , & , . , ' , ) , % , ^ , + , * etc. I would like to escape all such characters that might cause a regex to fail on this string in Java. Javascript has something like this in one of the posts which goes like this-
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
Is there something similar for Java? I'm not sure what should be the character set to escape. Would something like str.replaceAll("[^\u0000-\u00ff]+", " ") do that? (But I'm losing data here if I'm replacing ALL of them with a space, which I want to avoid)
Use this:
String myEscapedString = Pattern.quote(myRawString);

String .replaceAll() unexpected behaviors while getting data from Sqlite database

I am wondering with this behavior. In my application I am getting data from server , or my own created database. ( I clone server database)
.replaceAll ( "\r\n" , "<br/>" ) ;
When the data is come from server that it replace. But When data is get from sqlite database its unable to replace the above. As I have try .replaceAll ( "a" , "??" ) ; and its working.
The database data is
Bradley Ambrose is the freelance cameraman who recorded the John Key and John Banks tea meeting.\r\n\r\nHe intentionally placed a black bag with a recording device on the table where Key and Banks were sitting, although he claims it was a mistake, If that were true then how did so many people get a copy of it???\r\n\r\nAlso this guy bloody changed his name from Brad White what the hell is this guy an international man of mystery or something.
I have also debug that issue in detail. But the is not replaced even code is executed the above line successfully.
I have also try
replaceAll ( "\n" , "<br/>" )
replaceAll ( "\r" , "<br/>" )
There is debugging picture.
Does the input string contain actual CR and LF characters or pairs of \ and r and \ and n?
The regex won't work in latter case. It would require .replaceAll("\\\\r\\\\n" , "<br/>")
Can you try with Pattern#quote() ?
Something like:
System.out.println("hello\r\n\r\n something".replaceAll(Pattern.quote("\r\n"), ""));
The code is fine. The data you are seeing in the debug screen is wrong. Do the same debug session and insert a system.out.println and check the output with the output in the debug screen.
Unless you you mean the database actually has the string "\r\n". The above assumes that the database actually contains the carrige return and line feed characters. If your database actually has the backslash character followed by the 'n' character then your regex needs a simple tweak. s.replaceAll("\\\\r\\\\n", "")

Categories