-1

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.

flagg19
  • 1,782
  • 2
  • 22
  • 27
  • Does this answer your question? [How to convert Java String to JSON Object](https://stackoverflow.com/questions/29182842/how-to-convert-java-string-to-json-object) – fantaghirocco Feb 26 '21 at 14:08
  • @fantaghirocco thanks for helping, but, no, I don't think it's the same thing I'm asking here – flagg19 Feb 26 '21 at 15:02

1 Answers1

0

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

Sorin
  • 977
  • 3
  • 12
  • Thanks but that's not what I want. I know that \ is a spacial character, I used it in the example to be able to put some "spicy" chars in the string, I didn't intend to have the actual \ in the string. I don't want to get the original string form the jsonObj, I want to have the original string encoded as json, but still a string, not an object! I want a string that is a valid json and once decoded is again the original string, but just the string, I don't want to put it inside a dictionary or array. – flagg19 Feb 26 '21 at 15:46