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

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

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

Groovy: convert JSON array to URLencoded string?

I am writing an app for SmartThings (www.smartthings.com) in their own IDE. I have an input field here that is supposed to be text input. I ask for a departure address:
section("Departing From:"){
input "departFrom", "text", title: "Address?"
}
when putting in the value of Monterey, CA the value magically gets changed to a JSON Array with the values of [Monterey, CA]
I want to pass this value to an httpGET statement but I need to URLencode it first to omit spaces, etc.I have tried URLencoder with no success due to the JSON array.
I have tried join(",") with no luck as it adds double quotes to the value.
How can I get a clean Monterey%2C%20CA URL encoded value from this variable?
** bear in mind someone could input any combination of numbers, spaces, and commas into this input as an address. The mapquest API I am sending it to can handle all these things as long as they dont have special characters and spaces are URL encoded.
Maybe try:
def l = ['Monterey', 'CA']
assert URLEncoder.encode(l.join(', ')).replaceAll('\\+','%20') == 'Monterey%2C%20CA'
When it comes to replacing + sign, please see here
There are different types of URL encoding, but in this case there are two: One that converts spaces to %20 and one that converts spaces to +.
For the first, you'd use UriUtils:
def yourEncodedString = UriUtils.encodeUri(yourString.toString(), "UTF-8")
For the second, you'd use UrlEncoder:
def yourEncodedString = URLEncoder.encode(yourString.toString(), "UTF-8")
Alternatively (I think) you can use URLEncoder with UTF-16 to get what you want.
I've never had a fun time with UriUtils, so hopefully UrlEncoder will work for you.

Convert JSON unicode characters to unicode value

Basically, when JSON takes in a string it will convert things like ' or & to their Unicode value. I'm trying to store the JSON value as it goes out, and when it comes back in later, compare it with the JSON value. However, when I send out something like "Let's Party" it comes back "Let\u0027s Party"
So basically, I'm looking to convert all JSON Unicode to their specific Unicode values before storing it or sending it out.
I'm looking to convert all JSON Unicode to their specific Unicode values
I doubt you want to convert all characters to \u-escapes. In that case Let's party would become \u004c\u0065\u0074\u0027\u0073\u0020\u0050\u0061\u0072\u0074\u0079.
There is nothing special about the apostrophe or ampersand that means it has to be encoded in JSON, although some encoders do so anyway (it can have advantages for using JSON inside another wrapper context where those characters are sepecial).
It looks like you want to match the exact output that another encoder produces. To do that you'd have to determine the full set of characters that that encoder decides to escape, and either alter or configure your own JSON encoder to match that. For some characters that could be as simple as doing a string replace: for example as ' may only legitimately appear in JSON as part of a string literal it would be safe to replace with \u0027 after the encoding. This is ugly and fragile though.
It is generally a bad idea to rely on the exact encoding choices of a JSON serialiser. The JSON values {"a": "'", "b": 0.0} and {"b": 0, a: "\u0027"} represent the same data and should generally be treated as equal. For comparison purposes it is usually better to parse the JSON and check the content piece-by-piece, or re-serialise using your own encoder and compare that output (assuming your JSON encoder is deterministic).

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.

Android- remove URL percent symbols from string

I have a URL that looks like this:
Liberty%21%20ft.%20Whiskey%20Pete%20-%20Thunderfist%20%28Original%20Mix%29.mp3
I'm trying to extract just the words from it. Right now, I'm using string.replace("%21", "!") for each and every %20, %29, etc. because each segment represent different characters or spaces. Is there a way to just covert those symbols and numbers to what they actually mean?
Thanks.
Those symbols are URLEncoded representations of characters that can't legally exist in a URL. (%20 = a single space, etc)
You need to UrlDecode those strings:
http://icfun.blogspot.com/2009/08/java-urlencode-and-urldecode-options.html
Official documentation here:
http://download.oracle.com/javase/6/docs/api/java/net/URLDecoder.html
It seems the input string is written using the URL encoding. Instead of writing all possible replacements manually (you can hardly cover all possibilities), you can use URLDecoder class in Java.
String input = "Liberty%21%20ft.%20Whiskey%20Pete...";
String decoded = URLDecoder.decode(input, "UTF-8");

Categories