javax.json.JsonException: Unexpected Char=155 when creating jsonArray - java

I'm trying to do some parsing with JSON file simply getting the key and value from JSON and passing it into jsonArray then create hashmap from array.
My code works for most of the JSON files I encounters but doesn't work for one file (its huge and somewhat confidential). The error I'm getting is
Exception in thread "AWT-EventQueue-0" javax.json.JsonException: Unexpected Char=155
at org.glassfish.json.JsonTokenizer.readString(JsonTokenizer.java:168)
at org.glassfish.json.JsonTokenizer.nextToken(JsonTokenizer.java:302)
at org.glassfish.json.JsonParserImpl$StateIterator.nextToken(JsonParserImpl.java:158)
at org.glassfish.json.JsonParserImpl$StateIterator.next(JsonParserImpl.java:183)
at org.glassfish.json.JsonParserImpl.next(JsonParserImpl.java:151)
at org.glassfish.json.JsonReaderImpl.readObject(JsonReaderImpl.java:184)
at org.glassfish.json.JsonReaderImpl.readArray(JsonReaderImpl.java:152)
at org.glassfish.json.JsonReaderImpl.readArray(JsonReaderImpl.java:127)
at parserUI.js2Properties(parserUI.java:173)
and my line 173 is this
JsonArray array = jsonReader.readArray();
Do you have any idea what is causing this? The format of json are generally as this
[
{
"key":"aaaa",
"value":"bbbbb",
"description":""
},
{
"key":"cccccc",
"value":"dddddd",
"description":""
},
]
I found which line is causing the issue
its this
"value":"查看活动",
but if then created an identical line(shown below) to replace it, then it works
"value":"查看活动",
they are identical but one works and one doesn't
...can anyone explain this?

There might be special characters or hidden characters or non printable unicode characters which might be there in input. Try to remove these type of characters with regex and then try.

Related

Parse Exception for special characters

I have a string str where
str = {"name":"vicky"12/3","pwd":""pwd":myPassword/123""}.
When I am passing the string in the JSONParser(org.json.simple.parser.JSONParser) I am getting the parse exception.
Here str may vary depending on different input.
Tried with JSONObject.escape(str). But then it is giving the error as Unexpected character (\) at position 1.
Please anyone suggest so that parser will parse correctly and using that a JSON object will be constructed so that json.get("name") and json.get("pwd") will return correct result where json is the object of JSONObject.
Thanks in advance.

Wrong JSON array in JAVA, and added back slash in URL

I have the following JSON array which I use POST method to send it to BackEnd:
{"images":
[["https:\/\/storage.googleapis.com\/shelf-prove\/test1.jpg",
"https:\/\/storage.googleapis.com\/shelf-prove\/test2.jpg",
"https:\/\/storage.googleapis.com\/shelf-prove\/test3.jpg",
"https:\/\/storage.googleapis.com\/shelf-prove\/test5.jpg"]],
"skus":["
{\"id\":5179846254657536,\"coordinates\":\"137,447,692,438,690,610,140,617\",\"sku\":\"Biscotti\"}",
"{\"id\":5656058538229760,\"coordinates\":\"0,116,303,104,310,264,2,282\",\"sku\":\"Riso\"}",
"{\"id\":5765606242516992,\"coordinates\":\"140,614,675,610,673,751,145,755\",\"sku\":\"Succo\"}"],
"percentage":"33",
"model":5682617542246400,
"shelf":5660980839186432
}
in Java I try to get it as JSON array with the following code :
imagesToProcess = json.getJSONArray("images");
for(int i = 0; i < imagesToProcess.length(); i++){
String src="";
src = imagesToProcess.getString(i); }
the problem is that in java i see the value of the array as following:
[["https:\/\/storage.googleapis.com\/shelf-prove\/test1.jpg","https:\/\/storage.googleapis.com\/shelf-prove\/test2.jpg","https:\/\/storage.googleapis.com\/shelf-prove\/test3.jpg","https:\/\/storage.googleapis.com\/shelf-prove\/test5.jpg"]]
and in for loop, the value of each lement is like this:
[["https:\/\/storage.googleapis.com\/shelf-prove\/test1.jpg","https:\/\/storage.googleapis.com\/shelf-prove\/test2.jpg","https:\/\/storage.googleapis.com\/shelf-prove\/test3.jpg","https:\/\/storage.googleapis.com\/shelf-prove\/test5.jpg"]]
I don't know what's the problem!
The Reason why This is Happening:
A Valid JSON String will always Contain "\" before "/" for Representation.
See Image:
what JAVA Does here is Converts the JSON to a Valid JSON by adding "\" before "/" .
The Solution is to Process the String in JAVA and convert it to Original Format by removing '\' character occurences from String
For that You can Refer to Answer:
remove-all-occurrences-of-char-from-string
To answer your probably in order, you are trying to get the value for an array of array, this looks like an mistake of encoding since the first array is of 1 cells. So get the array in that cell then iterate, you have a correct code for that.
Then about the escaped character, you can see in the RFC 7159 - The JavaScript Object Notation (JSON) Data Interchange Format
From 7. Strings :
Any character may be escaped.
But there is no specification about which one, you can see in an example :
"Thumbnail": {
"Url": "http://www.example.com/image/481989943",
"Height": 125,
"Width": 100
},
The URL has no escape "/" so this is API specific.
There is know question about that problem on SO like :
JSON: why are forward slashes escaped?
Why is the slash an escapable character in JSON? [duplicate]

Json parser to catch trailing commas in Java?

I was using the following to check if a json file was valid:
JsonParser parser = new JsonParser();
parser.parse(new String(Files.readAllBytes(Paths.get((filePath.toString())))));
But the json file I am validating has trailing commas like below that it doesn't throw an exception for:
"file":"hello.htm"},]
Since this is the last attribute the comma isn't needed and is causing trouble in other areas of our application. Is there a parser or some way to catch this trailing comma?
Assuming JsonParser is part of Gson, you're currently out of luck. Gson's parsing currently interprets the trailing comma in a JSON array as a null value. It's wrong and a resolution seems to be planned for Gson 3.
In the meantime, you can use a different parsing library. I suggest Jackson. If you're just validating the JSON, you can use
ObjectMapper mapper = new ObjectMapper();
mapper.readTree(Files.readAllBytes(Paths.get(filePath.toString())));
This will throw an exception, with a message similar to
Unexpected character (']' (code 93)): expected a value
indicating that it expected an actual value after the ,, not the closing array symbol.
When iterating the JSONArray, you could ask if the element is null:
for (i in 0 until jsonArray.length()) {
if (!jsonArray.isNull(i)) {
// parse here...
}
}
And then you would be able to avoid the 'org.json.JSONException' exception.

java creating JSONArray from a String: org.json.JSONException: Bad character ':'

I get a String in the following format:
String buffer = "[{\"field1\": 11,\"field2\": 12,\"field3\": 13}]";
and want to convert it to a JSONArray.
Thus i use the following code:
JSONArray Jarray = CDL.toJSONArray(buffer);
My Problem is now i get the following exception:
org.json.JSONException: Bad character ':' (58). at 24 [character 25 line 1]
at org.json.JSONTokener.syntaxError(JSONTokener.java:432)
at org.json.CDL.rowToJSONArray(CDL.java:113)
at org.json.CDL.toJSONArray(CDL.java:193)
at org.json.CDL.toJSONArray(CDL.java:182)
at MyDataexchange.MyCVSConverter.convertJson(MyCVSConverter.java:44)
at Mainexe.DataTest.main(DataTest.java:22)
As you can see in the stacktrace i want to use this to convert the string to .cvs at the end.
Since i dont know how to do it in a better way i'd like to know how to fix this exception.
Do i need to substitute the ':' with anything?
(Substitue ':' to ',' would produce null for example but not throw an exception, still it doesnt help me)
If yes it would be nice to tell me with what, otherwise any suggestions are welcome.
org.json.CDL is for parsing and serializing comma delimited text. However, your sample string is not comma delimited text. It's JSON. You probably wanted JSONArray Jarray = new JSONArray(buffer)
Ok, here's a better way of doing this (similar to what "guest" said):
String s = "[{\"field1\": 11,\"field2\": 12,\"field3\": 13}]";
Object obj=JSONValue.parse(s);
JSONArray array=(JSONArray)obj;

Combination of Specific special character causes Error

When I am sending a TextEdit data as a JSON with data as a combination of "; the app fails every time.
In detail if I am entering my username as anything but password as "; the resultant JSON file looks like:-
{"UserName":"qa#1.com","Password":"\";"}
I have searched a lot, what I could understand is the resultant JSON data voilates the syntax which results in throwing Default exception. I tried to get rid of special symbol by using URLEncoder.encode() method. But now the problem is in decoding.
Any help at any step will be very grateful.
Logcat:
I/SW_HttpClient(448): sending post: {"UserName":"qa#1.com","Password":"\";"}
I/SW_HttpClient(448): HTTPResponse received in [2326ms]
I/SW_HttpClient(448): stream returned: <!DOCTYPE html PUBLIC ---- AN HTML PAGE.... A DEFAULT HANDLER>
Hi try the following code
String EMPLOYEE_SERVICE_URI = Utils.authenticate+"?UserName="+uid+"&Email="+eid+"&Password="+URLEncoder.encode(pwd,"UTF-8");
The JSON you provided in the Question is valid.
The JSON spec requires double quotes in strings to be escaped with a backslash. Read the syntax graphs here - http://www.json.org/.
If something is throwing an exception while parsing that JSON, then either the parser is buggy or the exception means something else.
I have searched a lot, what I could understand is the resultant JSON data voilates the syntax
Your understanding is incorrect.
I tried to get rid of special symbol by using URLEncoder.encode() method.
That is a mistake, and is only going to make matters worse:
The backslash SHOULD be there.
The server or whatever that processes the JSON will NOT be expecting random escaping from a completely different standard.
But now the problem is in decoding.
Exactly.
Following provided JSON can be parsed through GSON library with below code
private String sampledata = "{\"UserName\":\"qa#1.com\",\"Password\":\"\\\";\"}";
Gson g = new Gson();
g.fromJson(sampledata, sample.class);
public class sample {
public String UserName;
public String Password;
}
For decoding the text I got the solution with..
URLDecoder.decode(String, String);

Categories