Does the colon character fit with JSON? - java

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.

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

split JSON and string in android

My HTTP Request responds with combination of string and JSON, something like this:
null{"username:name","email:email"}
I need only the JSON part.
I directly tried parsing as json object, which was not right of course. I tried splitting it: serverResponse.split("{"), but android does not allow to parse with this character because it is not a pattern. Any suggestion how i can achieve this?
String.split uses regular expressions, and since '{' is a special character in regular expressions, you should escape it like this: serverResponse.split("\\{").
It would be better to change the server side, but you can also just use split. The only thing you need to do is escape your {.
String json = serverResponse.split("\\{")[1];
It is a bad idea and a bad practice to split a Json. If one day it you change on the serve side, it may pick a wrong part of your Json Object.
I recommend you to PARSE it, even if it is simple and small.

Using regex to remove JSON quotes

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

Reading Json data containing special symbols like curly braces, square brackets etc

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).

Non Json Format to JSON format

I have a string which is 'almost' a json string, only that its keys are not surrounded by quotes.
Normally it is used by the UI and javascript which does not have a problem in interpreting it. However it seems the JSON parsers in Java that i know of require key to be surrounded by quotes.
Is there a way i can convert the string to a valid json string, probably by using a regular expression in Java.
Or is there a JSON lib which is a bit lenient.
The String will be of the form
{
A : "Val1",
B : [ SOME NESTED STUFF],
C : "Val3"
}
and i need to convert it to
{
"A" : "Val1",
"B" : [ SOME NESTED STUFF],
"C" : "Val3"
}
without affecting any of the nested stuff. The number of keys ie A, B, C is fixed.
Thanks
P.S. I cannot get the appropriate JSON string returned to me, it is a pre existing code and it is quite risky to change it.
If you happen to use Jackson it has support for non-standard JSON including unquoted keys: http://www.cowtowncoder.com/blog/archives/2009/08/entry_310.html
If you are sure that all line starting with     unquoted_word : need the word to be quoted, you could use something like:
str.replaceAll("(?m)^(\s+)(\w+)(\s*:)", "$1\"$2\"$3");
But if you can you are probably better off using a proper parser like other answers suggest.
If you really want a regex, this might work:
jsonString.replaceAll("(\\w+)\\s*\\:","\"$1\" :");
That said, if you are really worried about touching the nested stuff and corner cases, you want a real parser, not a regex. There's no way that a regex will be precise enough to avoid messing up if one of your values is the string " A : ". If pingw33n is correct about the jackson parser, it is by far the best answer.
use the following line code to enclose all the keys (single caps letter is considered a valid key here) with double quotes:
str = str.replaceAll("\s([A-Z])\s\:\s\"", "\"$1\" : ");

Categories