Take non-nested JSON String and Build Json Nested String - java

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.

Related

How to convert String to Json Object in java or groovy

I saved a json into the database as a string like this:
"[_district:_1_2_5village, _name:_1_1_2id_inter, _gender:_1_3_5sex]"
Now i want to convert it back to a Json Object so as to pick the key and value eg _district is the key and _1_2_5village is the value. Any help on how i can achieve this. Thanks
I tried to convert the string back into JSON by parsing but that dint work for me.
It doesn't work because that's not a JSON format, a JSON is a way of mapping objects and uses key value syntax like so:
{"key": "value"}
and an array would look like this:
[{"key": "value"},{"key": "value"}]
You'll need to make a custom parser for your syntax
Here's the json specification:
https://www.json.org/json-en.html

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?

Mongo database Invalid BSON field name exception

I tried to follow this How to use dot in field name?. But it result as the picture. There is a additional space:-
protected Document setNestedField(Document doc, FieldValue parentField, String nestedFieldName, Object value, boolean concatenate) {
if (concatenate) {
doc.put(parentField.getSystemName() + "." + nestedFieldName, value);
}
else {
doc.put(nestedFieldName, value);
}
return doc;
}
Exception:-Invalid BSON field name photographs.inner_fields; nested exception is java.lang.IllegalArgumentException: Invalid BSON field name photographs.inner_fields.
How can I use dot "." in field name. I have to use . as I'm using some 3rd party api and I have no option to replace to something else like [dot]. Please suggest me?
In MongoDB field names cannot contain the dot (.) character as it is part of dot-notation syntax, see the documentation.
What third party API are you using ? Are you sure you need a dot ? Dots are commonly used when parsing JSON and your third party API should not need it.
So, a third party api is both constructing the keys (with periods in them), AND saving that to MongoDB?
I suggest that you open a bug ticker in said API:s tracker.
If this is not the case, encode the periods somewhere in the persistence code - and decode it on the way up.

Anyway to overwrite parts of a json file in java?

I need to be able to parse sql calls from a database to json and then compare the key fields in the parsed JSON string against a json file (it's technically a BOD --Business Object Document) and if they match then I need to overwrite the json file's matching value with that of the JSON string.
e.g. I parse the sql call to this
{
"partyInfo": {
"PARTY_NAME": "NORWAY",
"STATE": "OSLO",
"PARTY_ID": "92706031",
"VERTICAL_MARKET_TOP_DESC": null,
"ATTRIBUTE20": null,
"DUNS_NUMBER": null,
"SIC_CODE": null,
"EMPLOYEES_TOTAL": null,
"ALL_ADDRESS_LINES": "HOMMENKOLLEN 23 TOPPEN 12",
"CITY": "OSLO",
"POSTAL_CODE": "1255",
"COUNTRY_NAME": "NORWAY",
"KNOWN_AS": null
}
}
and then compare it against a file that looks like this:
{
"partyInfo": {
"PARTY_NAME": string,
"STATE": string,
"PARTY_ID": number,
"SIC_CODE": string,
}
}
and overwriting values on matching keys s.t that the ending file looks like this:
{
"partyInfo": {
"PARTY_NAME": "NORWAY",
"STATE": "OSLO",
"PARTY_ID": "92706031",
"SIC_CODE": null,
}
}
So far I've been able to parse the SQL calls to JSON (using Jackson right now but I'm willing to change if need be) but I don't know how to compare against the file and overwrite only the data values that match up.
It looks like the tree model allows you to update nodes.
Here's an example:
http://wiki.fasterxml.com/JacksonInFiveMinutes#Tree_Model_Example
I may be misunderstanding what you're wanting to do, but it sounds like you could just use a for loop over the keys in the Map representing the JSON from the file, compare the values to those in the database, change any that don't match, and then write the file back out:
for(String key: fileJson.keys())
if(!fileJson.get(key).equals(sqlJson.get(key)))
fileJson.put(key, sqlJson.get(key));
// write fileJson back out to the correct file through Jackson
The simplest solution would be to parse these files into java objects (using Jackson again), compare the objects and then save what you need to save.
Otherwise you'll effectively be making something like the patch tool.

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