I am having an escaped string in a variable and I am trying to make JSON object out of the string. It's throwing the Exception which looks like this :
org.json.JSONException: Missing value at character 1
After thorough research, I couldn't find an answer in a stack overflow.
But finally, I found a clue and got rid of this problem. I want to share the solution so that others won't waste much of their time in this.
If the string is escaped you need to unescape it before trying to make JSONObject out of it. Below is the sample snippet.
String escapedString = StringEscapeUtils.unescapeJava(escapedString);
JSONObject Json = new JSONObject(escapedString);
I open to hear any other best solutions other than what I mentioned here.
Adding further details about your approach -
Deprecated - org.apache.commons.lang3.StringEscapeUtils
Correct reference - org.apache.commons.lang3.StringEscapeUtils
Related
I need to convert
{"officeId":1,"clientId":97,"resourceId":97}
Please note that for values I don't have quotes. I have seen similar questions asked and answered, i haven't seen one that looks exactly like this one, i.e values have no quotes in the string to be converted.
Here's the original string from REST server
"{\"officeId\":1,\"clientId\":98,\"resourceId\":98}"
Are you getting an error? You shouldn't be because it's valid JSON. If you quote the numbers, they're now strings instead.
See Can JSON numbers be quoted.
A regular parse will suffice:
JSONObject jsonObj = new JSONObject("{\"officeId\":1,\"clientId\":98,\"resourceId\":98}");
In my API response, I have control-p character. Jackson parser fails to serialize the character and throws an error
com.fasterxml.jackson.core.JsonParseException: Illegal unquoted
character ((CTRL-CHAR, code 16)): has to be escaped using backslash to
be included in string value
I have investigated and found that Jackson library actually tries to catch for ctrl-char.
Can anyone suggest solutions or work around for this? Thanks in advance.
I was able to fix similar problem by setting Feature.ALLOW_UNQUOTED_CONTROL_CHARS (documentation) on JsonParser
.
The code in my case looks:
parser.setFeatureMask(parser.getFeatureMask() | JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS.getMask());
As stated by others, such JSON is invalid, but in case you have no chance to change JSON, this should help.
Have you tried to configure the mapper to force escape non-ASCII?
This might be enough:
mapper.configure(JsonGenerator.Feature.ESCAPE_NON_ASCII, true);
see documentation
But I agree with StaxMan: the JSON response should be well formatted.
Content you get is not valid JSON -- as per JSON specification, control characters MUST be escaped within String values, and CAN NOT exist outside of them. So I would recommened getting input data fixed; it is corrupt, and whoever is sending it is not doing good job of cleansing it, or properly escaping.
Barring that, you can write a Reader (or even InputStream) that filters out or converts said control characters.
I want to extract the value 0.81 from the following string, but I don't know how. Using JSON doesn't work, because as far as I know it's not proper JSON code.
[{"boundingbox":{"size":{"height":239.23,"width":239.23},"tl":{"y":46.15,"x":166.92}},"name":"152:0.81,","confidence":0.9}]
Do you have any idea how to do that?
If this is JSON, which it appears to be, load it up as a JSON Object and
JSONArray jsonArray = new JSONArray(thatString);
JSONObject jObj = jsonArray.getJSONObject(0);
String name = jObj.getString("name");
Which would then give you a string "152:0.81,", an odd name - however I would then split it:
String[] tokens = name.split(":");
tokens[0] will be 152
tokens[1] will be 0.81,
It actually is valid Json, so you could use Json library (any of them), to load the Json to an Object and access the value - If you're having problems loading this into an Object, perhaps you can change your question and show us the error?
If, by any chance, you might get a response that isn't valid Json, you might use a regex:
If you always have that same pattern, something like:
\"name\":\"\d+:(\d\.\d+),\"
Your value will be in capturing group one.
If you're not sure how to use regexes in Java, just search SO or Google, there's a ton of examples.
I am being given some JSON from an external process that I can't change, and I need to modify this JSON string for a downstream Java process to work. The JSON string looks like:
{"widgets":"blah","is_dog":"1"}
But it needs to look like:
{"widgets":blah,"is_dog":"1"}
I have to remove the quotes around blah. In reality, blah is a huge JSON object, and so I've simplified it for the sake of this question. So I figured I'd attack the problem by doing two String#replace calls, one before blah, and one after it:
dataString = dataString.replaceAll("{\"widgets\":\"", "{\"widgets\":");
dataString = dataString.replaceAll("\",\"is_dog\":\"1\"}", ",\"is_dog\":\"1\"}");
When I run this I get a vague runtime error:
Illegal repetition
Can any regex maestros spot where I'm going awrye? Thanks in advance.
I believe you need to escape braces. Braces are used for repetition ((foo){3} looks for foo three times in a row); hence the error.
Note: in this case it needs to be double escaping: \\{.
{ and } in regex have special meaning. They are to mention allowed repetition of patterns. So they are to be escaped here.
Use \\{\"widgets\":\"", "\\{\"widgets\": instead of {\"widgets\":\"", "{\"widgets\":.
Since the input string looks to be valid json, your best bet would be to parse it with an actual parser to a map-like structure. Regexes are not the right tools for this. Serializing this structure to to something not quite json would then be relatively simple.
I do wonder if you're better off taking the code for JSONObject and modifying the toString() method to make this a more reliable transformation than using regexps. Here's the source code, and you're looking for invocations of the quote() method
Well, why don't you simply do the following?
1) Decode the first JSON (which is correct with quotes) into varJSON1
2) Get the String "blah" in varJSON1 into varJSON2
3) Then decode the varJSON2
I have a Java string which looks like this, it is actually an XML tag:
"article-idref="527710" group="no" height="267" href="pc011018.pct" id="pc011018" idref="169419" print-rights="yes" product="wborc" rights="licensed" type="photo" width="322" "
Now I want to remove the article-idref="52770" segment by using regular expression, I came up with the following one:
trimedString.replaceAll("\\article-idref=.*?\"","");
but it doesn't seem to work, could anybody give me an idea on where I got wrong in my regular expression? I need this to be represented as a String in my Java class, so probably HTMLParser won't help me a lot here.
Thanks in advance!
Try this:
trimedString.replaceAll("article-idref=\"[^\"]*\" *","");
I corrected the regular expression by adding quotes and a word boundary (to prevent false matches). Also, in case you didn't, remember to reassign to your string after the replacement:
trimmedString = trimmedString.replaceAll("\\barticle-idref=\".*?\"", "");
See it working at ideone.
Also since this is from an XML document it might be better to use an XML parser to extract the correct attributes instead of a regular expression. This is because XML is quite a complex data format to parse correctly. The example in your question is simple enough. However a regular expression could break on a more complex case, such as a document that includes XML comments. This could be an issue if you are reading data from an untrusted source.
if you are sure the article-idref is allways at the beginning try this:
// removes everything from the beginning to the first whitespace
trimedString = trimedString.replaceFirst("^\\s","");
Be sure to assign the result to trimedString again, since replace does not midify the string itself but returns another string.