How can i parse json object containing slashes in java - java

I want to parse a windows path in java.
this is part of the json:
..."sslkey":"c:\usr\ssl\key.jks"
and this is the code:
JsonObject jsonargs = gson.fromJson(args[0], JsonObject.class);
SSLKEY = jsonargs.get("sslkey").getAsString();
I tried with \ also in the value, but the error that I have is:
Exception in thread "main" com.google.gson.JsonSyntaxException:
com.google.gson.stream.MalformedJsonException: Unterminated object at
line 1 column 133 path $.sslkey
Could you please tell me how I can fix this?
Thank you !

Thank you, i tried many things , it seems that : is also special char. I used base64 encode in php and base64 decode in java.. so all fine :)

Related

Getting JsonException while using JSONML.toJSONObject()

I'm using JSONML for converting xml String to JSONObject.
This is my xml String
"<soapenv:Body xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\"><jsonArray><jsonElement><message>entity is deleted<\/message><errorCode>ENTITY_IS_DELETED<\/errorCode><\/jsonElement><jsonElement><message>entity is deleted<\/message><errorCode>ENTITY_IS_DELETED<\/errorCode><\/jsonElement><\/jsonArray><\/soapenv:Body>"
when I try JSONML.toJSONObject() It gives me
Caused by: org.json.JSONException: Bad character in a name at 32 [character 33 line 1]
at org.json.JSONTokener.syntaxError(JSONTokener.java:433)
at org.json.XMLTokener.nextToken(XMLTokener.java:288)
at org.json.JSONML.parse(JSONML.java:173)
at org.json.JSONML.toJSONObject(JSONML.java:286)
at org.json.JSONML.toJSONObject(JSONML.java:304)
at com.thbs.automaton.commonUtils.TestcaseUtils.compareXml(TestcaseUtils.java:144)
... 57 more
Its due to the escape character (\). I tried resolving this by removing all the \ characters , which solved my problem. However I don't think its a good practice.
Can anyone suggest a better approach?
The "\"s shows the original String is not a "XML String". It is an "escaped XML String". You should find out why and how the XML String is escaped.
Maybe it because of transferring as JSON. In that case, you should transform the original(JSON) String into data String, so to say a XML String. With code like this
String xmlString = jsonParser(originalString, String.class);
after that run as yours
JSONML.toJSONObject(xmlString);

Error Parsing JSON String to JSONObject in Java

I have an application that stores this JSON String :
String message ="{\"uid\":\"1\",\"streetName\":\"road\",\"city\":\"London\",\"speedLimit\":20}"
Now I want to parse it back to a JSON Object, In order to do so I have this line:
JsonObject object = new JsonParser().parse(message).getAsJsonObject();
I am using Gson Library to parse it and use it as a JSON Object. However, I am getting this exception :
com.google.gson.stream.MalformedJsonException: Expected name at line 1 column 2 path $.
Update 1
I have tried this
String message = "{"uid":"1","streetName":"road","city":"London","speedLimit":20}";
JSONObject object = new JSONObject(message);
Now I get this exception:
Unterminated string at character 28 of {"uid":"1","streetName":"roa
I have tried lots of workarounds from multiple threads on StackOverflow but nothing is working and I have no idea why ?
You can Directly cast it to the JSONObject,
JSONObject response = new JSONObject();
String str = "{\"uid\":\"1\",\"streetName\":\"road\",\"city\":\"London\",\"speedLimit\":20}";
response = new JSONObject(str);
Now the string response has casted as Json response.
you code is fine and should work
please check on the import of the JsonParser in your java file (should be com.google.gson.JsonParser)
let know on the Gson version if the JsonParser is not the issue
your code should work, may be you need to check the dependencies as mentioned before.
I am using this dependency https://mvnrepository.com/artifact/com.google.code.gson/gson/2.8.0
here is an sscce that work https://github.com/SalehAly/test-gson
I found my problem.
The String I was processing was malformed for the source. Fixing the string was the answer in here. Nothing was wrong with how I parsed the string.
Thanks for all the answers and the help.

JSON file processing error: A JSONArray text must start with '[' at 1 [character 2 line 1] when use file in UTF-8 encoding

I have a valid JSON-file. I want to read it into a memory as JSONArray object.
In order to do that I use the following code (powered by Apache Commons IO 2.5):
String jsonTxt = FileUtils.readFileToString(new File(file.json), "UTF-8");
JSONArray itemsArr = new JSONArray(jsonTxt);
But I get the error:
Exception in thread "main" org.json.JSONException: A JSONArray text must start with '[' at 1 [character 2 line 1]
at org.json.JSONTokener.syntaxError(JSONTokener.java:433)
at org.json.JSONArray.<init>(JSONArray.java:106)
at org.json.JSONArray.<init>(JSONArray.java:145)
at myOrg.infomedia.dba.NewsSourcesData.loadNewsSourcesData(NewsSourcesData.java:39)
at myOrg.infomedia.main.Main.main(Main.java:65)
After multiple checks, I found out that the root of the problem is the file encoding. If I provide a file in UTF-8, it throws exception, but if I convert the file to ANSI everything is working correctly.
I'm using org.json version json-20160212.jar.
How can I get JSONArray from my JSON-file in UTF-8 encoding?
I think you have a file encode in UTF-8 with BOM try to convert file using Notepad++ or something similiar to UTF-8 without BOM

Getting JSON from SimpleClient http request using Buffered Reader and org.json, Null Pointer

I'm about to go to bed, but this issue has been the result of a good weekend of progress, and would like to end on a good note!
http://imgur.com/a/SW533
I am using Buffered Reader to get JSON from a get request to RIOT's endpoint. The data comes back fine - when I print it out, but when I try to append it to a String Builder object, it just doesn't... Hopefully it is just me being thick and maybe a problem with my understanding of how Java works.
In debug mode it shows both outcome and the string builder object as being null, but then how can it even print that out?
Thanks for any help in advance
You post error code in image by analyzing you json data and exception :
You may be passing the string to JSONObject with leading spaces. So you need trim string before passing JSONObject.
Replace this line by following code :
JSONObject json = new JSONObject(sb.toString().trim());

org.codehaus.jackson.JsonParseException: Unexpected character ('�' (code 65533 / 0xfffd))

I have a Json string in the database but while converting in Java object, it gives following error:
Caused by: org.codehaus.jackson.JsonParseException: Unexpected character ('�' (code 65533 / 0xfffd)): expected a valid value (number, String, array, object, 'true', 'false' or 'null')
Json is : {"crt":"wrd","name":"7|6A TTTM"}
In java code I have configured it and have made it private (not static final)
objectMapper= new ObjectMapper();
objectMapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
Note: It some time converts that Json string in Object but some time gives above error. Why this unexpected result comes?
Short answer solution: Remove the first occurrence of the extra added BOM text with a method, such as the following, should fix this issue:
public String cleanUpJsonBOM(String json) {
return json.trim().replaceFirst("\ufeff", "");
}
I had a similar issue which I documented in a blog post.
Hope this help!
this worked for me.
String formattedString = yourString.trim().replaceAll("\uFFFD", "");
Something is producing invalid UTF-8 sequence (or, mismatch of UTF-8 vs a single-byte encoding like ISO-8859-1), and Jackson detects this encoding problem. It has nothing to do with ACCEPT_SINGLE_VALUE_AS_ARRAY setting, as the exception comes from low-level JsonParser.
So you need to figure out why the JSON content to parse is corrupt.

Categories

Resources