I have an ArrayList of Strings that looks like this:
["Alice","Bob","Charlie",....]
I am not sure how many Strings I might be getting inside the list. While passing this JSON I need to preserve the double quotes around each name.
{
"variables" :{
"division" : "B",
"Names" : ["Alice","Bob","Charlie"]
}
}
I've stored all the Strings in a variable called ListOfNames. Below is the code I've tried.
"{\"variables\":{\"division\":\"B\",\"Names\":"+"\""+ListofNames+"\""}}"
I want my payload to look like this so that I can pass it as variables for a query:
{\"variables\":{\"division\":\"B\",\"Names\":[\"Alice\",\"Bob\"]}}"
I'm a bit confused about balancing the double quotes and backslashes and unable to balance out the escape sequences for the array variable.
Am I missing something here?
Related
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
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";
I am working on an app that has a huge .json database, a lot of the strings I need in the .json file have curly brackets ("{", "}") inside them, which I do not want, like this:
[
{
"name": "Whatever",
"entries": [
"If something something {28} + {41.6} something"
]
}
]
And I need to get the string as "If something something 28 + 41.6 something".
I remove them by fetching the string I need and using this method:
public String formatText(String text) {
String newtext = text.replaceAll("\\{", "").replaceAll("\\}", "");
return newtext;
}
That works but makes everything really slow.
I had other characters in the file, like "#", that I had no problem removing in a text editor by selecting all of them and replacing by the empty string. But if I use the same logic with the curly brackets it will also remove the json object brackets.
Anyone can think of a way to edit this file and remove only the brackets inside the strings?
(I've thought of making a method that copies the strings, formats them and send them to a new .json, but that would be really innefective timewise, because there is a lot of different values inside every object.)
If you wanna use the find/replace functionality of text editors - using IDE like intelij - there is an option to replace stuff by regex.
E.g. this (?=\S.)({|}) should cover your case with braces in string only, while not touching json syntax braces. If you have other unique cases - they should be included in regex. Example - https://regex101.com/r/wbIgKX/1
Though, I would propose to create a proper json parser class specifically to deal with your stuff.
If you are sure that the JSON file is formatted like your example, you can check whether the line contains anything else then whitespaces and { or }
If the line contains anything else, then replace the brackets
If not, then don't replace
Try this:
convert the json array into JObject and then you can grab each individual element. then parse through that and replace the curly brackets.
String example = jObject.SelectToken("entries");
"entries": [
"If something something {28} + {41.6} something"
]
hope this helps :)
I have tried multiple way to resolve this issue but directly you cannot replace it. There is way to do it , First iterate the json and check whether the line contains curly brace or not. If contains then you can use str.replaceAll("[{}]", " ");. This will remove the all the curly braces and gives you the string without braces.
The best way to achieve is:
final String finalString = listId.getList().stream().map(String::valueOf).collect(Collectors.joining(",")).toString();
listId is a JsonArray.
I try design a simple all purpose Data Structure that must be convertable to JSON and back. Since I have names and types I need to find an expression for that.
So I look for something like name+type or name<type> or name:type (which i like) or name|type or type[name].
Are there any problems with that? I mean the : is already taken so I need to enclose the name and type (which is always a good idea).
Anything I need to know?
The colon : is part of the JSON syntax so you must enclose a name that contains a colon (as any name) in double quotes ". This
{
"foo:bar": "BAR",
"foo:baz": "BAZ"
}
is valid JSON. Check it at http://jsonlint.com/
The very simple JSON syntax can be read on the JSON.org site.
I have json data saved as a string in a database. The structure of JSON data is fine with the problem that it contains regex expressions and even urls which contains curry braces {} or square brackets [] etc. I can replace some of special symbols with the encodings available e.g hex or decimal encodings. and do string manipulations to take care of these. I was just wondering is there another way for handling this situation. I am getting following exception for the strings containing this type of Json data.
org.json.JSONException: Expected a ',' or '}' at character 22891 of {"wires":[{"id"....so on
Please let me know if I need to elaborate more.
Here's the first thing coming to my mind:
When putting the thing in the database try php addslashes/stripslashes (assuming you are using php to contact the database).