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.
Related
I have a malformed JSON with "key":True instead of "key":true
So I'm getting the following error :
"com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'True': was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false')"
I can solve my problem with replace("True", "true") on string before to parsing the JSON string.
But I would like to do this automatically with handling error or something like that. Using Jackson config. Is it possible?
private static final ObjectMapper jsonMapper;
JsonFactory f = JsonFactory.builder()
.enable(JsonReadFeature.ALLOW_LEADING_ZEROS_FOR_NUMBERS)
.enable(JsonReadFeature.ALLOW_SINGLE_QUOTES)
.build();
jsonMapper = JsonMapper.builder(f).build();
JsonNode res = jsonMapper.readTree(content)
JSON-sample:
{
...,
"key" : True,
...
}
What you want is inherently impossible.
The parser needs to be able to distinguish between the tokens in order to know how to deal with the next portion of JSON because different JSON-elements should be treated in a different way.
There are only two valid non-String (not enclosed in quotations marks) boolean values: true and false (and null also would be successfully parsed as false). And parsing algorithm depends on them, because it needs to be able to recognize the tokens.
boolean values represented as String, i.e. enclosed in quotations marks, are parsed in the case-insensitive manner automatically without any customization. And for non-String boolean values no formatting features which allow to tweak the behavior of the parser exist.
I'm afraid that there's no other way to solve the problem other then preprocess the JSON adjusting boolean values.
It seems you already know the answer.
You have malformed JSON, and malformed JSON IS NOT JSON.
Jackson ObjectMapper is a JSON processor.
If you want to know more detailed specification and implementation, please refer to the link below:
https://www.json.org/json-en.html
https://github.com/FasterXML/jackson-core/blob/jackson-core-2.14.1/src/main/java/com/fasterxml/jackson/core/json/UTF8StreamJsonParser.java#L741
I'm using Jackson 2.6.5.
I'm trying to read the following JSON:
{
"metadata1":"value",
"metadata2":"value"
}
{
"field1":"value",
"field2":"value",
....
}
With the following code:
JSONObject jsonObj = new JSONObject(jsonString);
But jsonObj contains only the "first" part of my JSON (the metadata), How can I read the "second" part of my JSON? (the part with the fields)?
EDIT
I know that my JSON doesn't contain "," so how can I parse it without "," between the jsons?
Seems like the JSON you added is missing a , sign between the two objects.
If you get such an non-json as input string, you might want to consider to:
First manipulate the input string by adding it the missing , . E.g. find the location of }{ and replace it with },{
And only then to insert it to the jackson
Your json is invalid, so you can't parse invalid json scheme by json parsing tools out of the box,
Instead you could read file by yourself into 2 strings - one valid json per string and then parse it with any json parser.
I am trying to convert Json String into Java Object. It is working for other inputs just for one input its not working. Is their any other way to do this?
My code:
JsonParser parser=new JsonParser();
JsonObject sel=parser.parse(selectedTerritory).getAsJsonObject();
TmsMapItBuilderBean dataSet = new Gson().fromJson(sel, TmsMapItBuilderBean.class);
ArrayList dataList = dataSet.getResultList();
resultMapData = mapServiceDelegate.processAssetDataWithGeoCodeForTerritories(subId, dataList);
It shows the following error:
Error on json convert to object :com.google.gson.JsonSyntaxException:
com.google.gson.stream.MalformedJsonException: Unterminated object near
ddress' :'2500 LEE'S CHAPEL RD', "stat
Your JSON is broken. You use a character that delimits the field's with which you are encoding your object. Use an escape to encode ' as a string.
Example:
{ 'name': 'tom\'s Hut' }
However as someone pointed out ' are not meant to be used for JSON Objects. I highly encourage you to use double-quotes.
{"name": "tom's Hut"}
Would be the correct way...
For more information on JSONs see: http://www.json.org/
I've tried the Simple JSON library and now I've turned to GSON but I'm getting a MalformedJSONException on a server's response string (of which I have no control over due to a fussy client *sigh*).
Have some code:
if (response.getStatusLine().getStatusCode() == 200){
String result = EntityUtils.toString(response.getEntity(), "UTF-8");
if (result != null){
StringReader reader = new StringReader(result);
JsonReader jsonReader = new JsonReader(reader);
jsonReader.setLenient(true);
JsonParser parser = new JsonParser();
JsonObject jsonOjb = (JsonObject)parser.parse(jsonReader);
.
.
.
}
}
The code will fail at parser.parse(jsonReader) and I'm pretty sure one of the reasons is due to this key-value in my response:
"itemdesc": Universal 7 " Boiling Ringplate (1800W),
I realise the value has no quotes around it, I'm hoping jsonReader.setLenient(true) will take care of that. But I've done some Googling on unescaped double quotes characters and Google seems to only tell me about instances when correctly escaped quotes \" get MalformedJSONExceptions. My problem is more the opposite!
So, I guess, my question is: is there a way for me to read my response one key-value pair at a time using GSON so that, if I run into an instance of an unescaped double quote, I can fix it? And failing that, would there be a cheap way to escape all instances of '"' with '\"'?
You should solve this at the source. Whatever is generating that JSON is broken and needs to be fixed.
I am using org.json to parse and write json. While serializing, i.e converting to string, I see json object adds an extra escape character. How can be this be avoided, if possible ?
String jsonStr = "{\"AD\":\"</p>\"}";
JSONObject jsonObject = new JSONObject(jsonStr);
System.out.println(jsonStr);
System.out.println(jsonObject.toString());
Output:
{"AD":"</p>"}
{"AD":"<\/p>"}
A number of other StackOverflow posts point out that this happens because (1) it is allowed by the JSON spec, and (2) it allows the JSON string to be inserted as-is into certain XML/HTML contexts that would otherwise not allow strings with "</" inside them.
If this causes problems, I would seek out A Better Java JSON Library--one that lets you define more character-escaping options.