Convert string to json object giving error - java

I have a string which needs to be converted to JSONObject, I added the dependency, but I'm getting error, which I'm not able to figure out. I have the following dependency:
<!-- https://mvnrepository.com/artifact/org.json/json -->
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20220924</version>
</dependency>
String s ="{name=Alex, sex=male}";
JSONObject obj = new JSONObject(s);
System.out.println(obj.get("name"));
I'm getting an exception:
org.json.JSONException: Expected a ':' after a key at line 5

The JSON you've provided is not valid because separator colon : should be used a separator between a Key and a Value (not an equals sign).
A quote from the standard The JavaScript Object Notation (JSON) Data Interchange Format:
4. Objects
An object structure is represented as a pair of curly brackets
surrounding zero or more name/value pairs (or members). A name is a
string. A single colon comes after each name, separating the name
from the value. A single comma separates a value from a following
name. The names within an object SHOULD be unique.
You can preprocess you JSON before parsing it using String.replace()
String s ="{name=Alex, sex=male}";
JSONObject obj = new JSONObject(s.replace('=', ':'));
System.out.println(obj.get("name"));
Output:
Alex
Also, note that Org.json (as well as some other libraries like Gson) would take care of fixing missing double quotes ". But it would not be the case with libraries like Jackson.

The string you're assigning to the variable s is not valid JSON. Property names and properties should be separated by : instead of =, and double quotes should be used around strings and property names.
So the string in your example should be like this (with \ being used to escape the quote characters within the string quotes):
String s = "{\"name\":\"Alex\",\"sex\":\"male\"}";

You should use : instead of =
String s = """{"name":"Alex","sex":"male"}"""; (Since Java 13 preview feature)

Related

How to Parse a Java String containing HTML element as JsonObject?

Hi I am having a Java String with following value received from HTTPRequest
{SubRefNumber:"3243 ",QBType:"-----",Question:"<p><img title="format.jpg" src="data:image/jpeg;base64,/9j/4AAQSkZJRgAB..."></img></p>"};
As the String contains HTML elements as part of it,while i try to parse the String as JsonObject as below (quesRow is the variable with above String as value)
JSONObject jsonObject = new JSONObject(quesRow);
I get parse error
org.codehaus.jettison.json.JSONException: Expected a ',' or '}' at character 103 of {SubRefNumber:"3243.....
I need to parse the HTML elements within Question Key as a seperate data from this JSONString. is there any way to handle this scenario? Please Guide...TIA
A valid JSON does not contain an unescaped quotation mark (") inside a string (See RFC 7159 Chapter 7 - https://www.rfc-editor.org/rfc/rfc7159#page-9).
There are different options to escape the quotation mark in your source string, already when putting it into the JSON string parameter:
escape with a backslash - "
escape as unicode sequence - \u0022

Java regex lookbehind

I want to match a string that has "json" (occurs more than 2 times) and without string "from" between two "json".
For example(what I want the string match or not):
select json,json from XXX -> Yes
select json from json XXXX -> No
select json,XXXX,json from json XXX -> Yes
Why the third is matching because I just want two "json" string occurs without "from" inside between it.
After learning regex lookbehind, I'm write the regex like this:
select.*json.*?(?<!from)json.*from.*
I'm using regex lookbehind to except the from string.
But after test, I find this regex match the string "select get_json_object from get_json_object" too.
What wrong for my regex? Any suggestion is appreciated.
You need to use tempered greedy token for achieving this. Use this regex,
\bjson\b(?:(?!\bfrom\b).)+\bjson\b
This expression (?:(?!\bfrom\b).)+ will match any text that does not contain from as a whole word inside it.
Regex Demo
For matching the whole line, you can use,
^.*\bjson\b(?:(?!\bfrom\b).)+\bjson\b.*$
Like you wanted in your post, this regex will match the line as long as it finds a string where a from does not appear between two jsons
Regex Demo with full line match
Edit:
Why OP's regex select.*json.*?(?<!from)json.*from.* didn't work as expected
Your regex starts matching with select and then .* matches as much as possible, while making sure it finds json ahead followed by some optional characters and then again expects to find a json string then .* matches again some characters then expects to find a from and finally using .* zero or more optional characters.
Let's take an example string that should match.
select json from json json XXXX
It has two json string without from in between so it should match but it doesn't, because in your regex, the order or presence of json and from is fixed which is json then again json then from which is not the case in this string.
Here is a Java code demo
List<String> list = Arrays.asList("select json,json from XXX","select json from json XXXX","select json,json from json XXX","select json from json json XXXX");
list.forEach(x -> {
System.out.println(x + " --> " + x.matches(".*\\bjson\\b(?:(?!\\bfrom\\b).)+\\bjson\\b.*"));
});
Prints,
select json,json from XXX --> true
select json from json XXXX --> false
select json,json from json XXX --> true
select json from json json XXXX --> true

Append double quotes in nested json string - Java

I have a nested json string like below for which I need to append double quotes for each key and value
{messageFilters:[{filterCriteria:[{paramNameAndVals:{},values:[abc[0-9]],context:Request,name:Destination-Host,operator:abc}],filterActions:[{paramNameAndVals:{Set
Name:sdf,Value To
Hash:as},context:Context,name:Stick-To-Pool}],name:MF}],name:fg1,subGroups:[],advancedView:false}
I want below output like ,
{"messageFilters":[{"filterCriteria":[{"paramNameAndVals":{},"values":["abc[0-9]"],"context":"Request","name":"Destination-Host","operator":"abc"}],"filterActions":[{"paramNameAndVals":{"Set
Name":"sdf","Value To
Hash":"as"},"context":"Context","name":"Stick-To-Pool"}],"name":"MF"}],"name":"fg1","subGroups":[],"advancedView":false}
I tried various regex patterns, but evrerything in vain. Could anyone please help
the first example of your question is not a valid json, try convert your not valid json to string.
kindly chechk this link for more information
How to convert any Object to String?

colon (:) within JSON data using Gson

I'm calling a web service that returns JSON. Within that JSON I have a property that holds a URL. But the colon (:) within that URL is making Gson throw a gson.stream.MalformedJsonException error. I know these keys and values should be wrapped
JSON returned by web service:
{
ID=15;
Code=ZPFgNr;
UserName=https://www.google.com/accounts/o8/id?id=xxxxxx; //<--problem
FirstName=Joe
}
My Java:
resultData=((SoapObject) result).getProperty(0).toString();
User response = gson.fromJson(resultData, User.class);
I know these keys and values should be wrapped in double quotes. But they are not, and that seems to be the problem.
So my question is:
Should I be encoding this JSON before deserializing it somehow? If so, how?
or
Should I do a find and replace on https: and escape the colon, If so, how would I escape the colon?
JSON uses commas to separate attributes, colon to separate the attribute name from the attribute value, and double quotes around the names and the values. This is not valid JSON.
Here's valid JSON:
{
"ID" : "15",
"Code" : "ZPFgNr",
"UserName" : "https://www.google.com/accounts/o8/id?id=xxxxxx",
"FirstName" : "Joe"
}

parsing a string by regular expression

I have a string of
"name"=>"3B Ae", "note"=>"Test fddd \"33 Ae\" FIXME", "is_on"=>"keke, baba"
and i want to parse it by a java program into segments of
name
3B Ae
note
Test fddd \"33 Ae\" FIXME
is_on
keke, baba
It is noted that the contents of the string, i.e. name, 3B Ae, are not fixed.
Any suggestion?
If you:
replace => with :
Wrap the full string with {}
The result will look like this, which is valid JSON. You can then use a JSON parser (GSON or Jackson, for example) to parse those values into a java object.
{
"name": "3B Ae",
"note": "Test fddd \"33 Ae\" FIXME",
"is_on": "keke, baba"
}
If you have control over the process that produces this string, I highly recommend that you use a standard format like JSON or XML that can be parsed more easily on the other end.
Because of the quoting rules, I'm not certain that a regular expression (even a PCRE with negative lookbehinds) can parse this consistently. What you probably want is to use a pushdown automaton, or some other parser capable of handling a context-free language.
If you can make sure your data (key or value) does not have a => or a , (or find some other delimiters that will not occur), the solution is pretty simple:
Split the string by , you get the key => value pairs
Split the key value => pairs by => you get what you want
if inputString holds
"name"=>"3B Ae", "note"=>"Test fddd \"33 Ae\" FIXME", "is_on"=>"keke baba"
(from a file for instance)
(I have changed the , to ; from between keke and baba)
String[] keyValuePairs = inputString.split(",");
for(String oneKeyValue : keyValuePairs)
{
String[] keyAndValue = oneKeyValue.split("=>");
}

Categories