Searching a key which is period separated using Boon api - java

I'm using Boon api for parsing a json string. In my json string one of the key is separated with a period example-(com.stack.demo). Now, the problem is that boon considers this period and separates the key. In short I'm trying to lookup a string in xpath fashion. In xpath you have a delimeter '[]' in which we can place the period separated string and xpath (json path) searches the string correctly.
I want to achieve the same through boon, any ideas...refer to the code below -
Map<String, Object> rickJsonList1 = (Map<String, Object>) Boon.fromJson(input);
System.out.println(Boon.atIndex(rickJsonList1, "eventHeader.com.schema.Header"));
The json is as below -
{"eventHeader" : {"com.schema.Header": "test"}}
I need to get the value "test"...

Have you tried bracket-notation?
?['eventHeader']['com.schema.Header']

Related

Convert string to json object giving error

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)

Take non-nested JSON String and Build Json Nested String

This is very new to me. I am reading data from a cassandra table. This data is being extracted via a "select json * ..." query but here's the thing. The format of that json is
{"acct_ref_nb": 1401040701, "txn_pst_dt": "2020-02-26", "txn_pst_tm": 1934131, "txn_am": 15000.0 ....
Every field is in quotation marks, followed by a colon, followed by the value, then a comma and the next field, so on and so forth.
We need to reformat this and have a nested structure. We also need to change the names of the fields. So you would have something like...
"{
"ccEvent": {
"account": {
"accountReferenceNumber": 1401040701,
"transactionPostDate": "2020-02-26",
"transactionPostTime": 1934131,
"transactionAmount": 15000.0,
........
Is there a preferred library to do this? I'm literally lost even at a high level on how to do this. Thanks.

Convert Map Object from String "[a:12,b:[a:b,c:d]]"

Is there any out of box method in java (groovy) that converts the string like
String s = "[a:12,b:[a:b,c:d]]";
to a Map object with key value pairs.
Update: It is somehow similar to the question asked as Groovy: isn't there a stringToMap out of the box?(Groovy: isn't there a stringToMap out of the box?). The difference is here the keys are of string type which makes easier to parse, since i have retrieved the mentioned map by doing .toString() i am unable to parse by the answered methods because my string actually contains date strings which i need it back to date objects. So it was difficult to parse the whole string.
You can convert this string to JSON-like format, and simple parse it:
String s = "[a:12,b:[a:b,c:d]]";
def result = new JsonSlurper().setType(JsonParserType.LAX).parseText(s.replaceAll('\\[', '{').replaceAll('\\]', '}'))
I have a way that may work depending on your actual data. The problem with your sample data is that you supply unquoted strings b and d as part of the structure:
String s = "[a:12,b:[a:b,c:d]]";
If what you had was actually
String s = "[a:12,b:[a:'b',c:'d']]";
or
String s = "[a:12,b:[a:1,c:2]]";
Then you could just do this:
def map=Eval.me(s)
but as is, eval tries to resolve b and d as variables which aren't defined in the scope.

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