String to JSONObject conversion in Java - java

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}");

Related

Conversion of String into Map in Java With Some Special Characters

I am trying to convert a String into Java Map but getting the following exception
com.google.gson.stream.MalformedJsonException
This is the string that I am trying to Map.
String myString = "{name=Nikhil Gupta,age=23,location=234Niwas#res=34}"
Map innerMap = new Gson().fromJson(myString,Map.class);
I understood the main problem here that because of these special characters I am getting this error.
If I remove those spaces and special characters then it will work fine.
Is there any way to do this without removing those spaces and special characters?
The approach used so far.
Wrapped those strings with special characters inside a single quote.
String myString = "{name='Nikhil Gupta',age='23',location='234Niwas#res=34'}"
But this is something that I don't want to use in a production environment as it will not work with nested structures.
Is there some genuine way to approach this in java?
I understood the main problem here that because of these special characters I am getting this error.
No, it's not because of "special characters" (whatever that means exactly).
{name=Nikhil Gupta,age=23,location=234Niwas#res=34}
The string you're trying to parse is simply not in JSON format, but in some other format that superficially resembles JSON. Your fixes by enclosing values in single quotes still don't make it JSON.
If it were valid JSON, it would look like this:
{"name":"Nikhil Gupta","age":23,"location":"234Niwas#res=34"}
Notable differences with your original:
Keys must be enclosed in double quotes
String values must be enclosed in double quotes (numeric values do not)
Key and value must be separated by a colon : instead of an equals sign =
Ways to solve this:
Use actual JSON format; see json.org for the specification
If you can't make it real JSON and you must absolutely use the format you are using, then you need to write your own parser for this custom non-JSON format

Java equivalent of Javascript: JSON.stringify("long_complex_string")

TL;DR: I have a String variable in java (not a json string, just a string) and I want to encode it to json, how? Please read the rest to be sure to have understood the question.
// This is javascript, I use it for this example because I know it better than java
// All of the following strings are valid json strings
const validJsonStrings = [
"{\"key\": \"value\"}",
"true",
"[]",
"\"long_complex_string\""
];
// Each of them can be parsed/decoded as you can easily test with:
console.log(validJsonStrings.map(s => JSON.parse(s)));
I'm interested in the 4th one, that is "\"long_complex_string\"" and that decodes into "long_complex_string".
Now, back to java, Let's say I have this variable:
String myString = "long_complex_string";
This is not json, it's just a string, it could be very long and could contain many special characters including double quotes. I want to encode this string to json, I want it to be exactly like the 4th string of the previous javascript example. I've seen many examples where objects or arrays are serialized to json, but I'm having trouble finding one that accepts a single string as input.
jsonObj.get("key") will retrieve only the stored value.
Please notice that \ is a special escape character for Java Strings. To get the desired String, your original has to look like this, escaping both \ and the ".
String original = "my ve\\\"ry c\\tomplex ✪string èè òòò ììì aaa";

How to remove this double quote before curly braces from this json string

I found no particular solution for my json string. I want to remove the double quotes from both end of the jsonObject. For better understanding I am sharing you the screenshot.
Thanks in Advance
If your JSON string format is the same you can use the following code to get your desired result:
jsonString = jsonString.replaceAll("(\"\\{\")","\\{\"").replaceAll("(\"\\}\")","\"\\}");
It simply removes all the leading and trailing double quotes from every array element.
You can convert your string into JSON using the following code:
JSONObject jsonObject= new JSONObject(jsonString);

Java Extract part of string

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.

How to add a URL String in a JSON object

I need to add a URL typically in the format http:\somewebsite.com\somepage.asp.
When I create a string with the above URL and add it to JSON object json
using
json.put("url",urlstring);
it's appending an extra "\" and when I check the output it's like http:\\\\somewebsite.com\\somepage.asp
When I give the URL as http://somewebsite.com/somepage.asp
the json output is http:\/\/somewebsite.com\/somepage.asp
Can you help me to retrieve the URL as it is, please?
Thanks
Your JSON library automatically escapes characters like slashes. On the receiving end, you'll have to remove those backslashes by using a function like replace().
Here's an example:
string receivedUrlString = "http:\/\/somewebsite.com\/somepage.asp";<br />
string cleanedUrlString = receivedUrlString.replace('\', '');
cleanedUrlString should be "http://somewebsite.com/somepage.asp".
Hope this helps.
Reference: http://docs.oracle.com/javase/6/docs/api/java/lang/String.html#replace(char,%20char)
Tichodroma's answer has nailed it. You can solve the "problem" by storing valid URLs.
In addition, the JSON format requires that backslashes in strings are escaped with a second backslash. If the 2nd backslash is left out, the result is invalid JSON. Refer to the JSON syntax diagrams at http://www.json.org
The fact that the double backslashes are giving you problems actually means that the software that is reading the files is broken. A properly written JSON parser will automatically de-escape the strings. The site I linked to above lists many JSON parser libraries written in many languages. You should use one of these rather than trying to write the JSON parsing code yourself.

Categories