Anyway to overwrite parts of a json file in java? - 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.

Related

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.

Get a dump of a section (object) of JSON

I'm looking to dump, rather toString() a section of JSON that I want to store locally as a string, since it it is highly variable and not imperative for me to know the contents.
I'm using JsonReader for the parsing:
https://developer.android.com/reference/android/util/JsonReader.html
Unfortunately, when I reach the token that contains what I want to dump, JsonReader does not have a method for dumping the entire JSON to a string.
This is the closest that it has:
https://developer.android.com/reference/android/util/JsonReader.html#toString()
It seems that I may have to use regex to pull out the value of the token I am targeting.
Is there another, better solution? How would I do this with regex?
Assume that this is the sample JSON and I am targeting the user key:
{
"id": 912345678901,
"text": "How do I read JSON on Android?",
"geo": null,
"user": {
"name": "android_newb",
"followers_count": 41
}
}

How to convert Map created from JSON to another Map in Java?

I got JSON file like this:
{
"issues": [
{
"no1": 5509,
"date": 1451520000
},
{
"no1": 6713,
"date": 1451433600
}],
"no2": [
220380,
163950,
213330,
215250,
174300]
}
I need to create a map issues where the no1 value will be key of the map and date value will be a value of the map. I've got already method which transfers JSON to map from file, and I know how to get the issues which will be: mapFromJson.get("issues"); what I get is:
issues=[{ no1: 5509.0, date: 1.45152E9}, {no1: 6713.0, date: 1.4514336E9}]
How to convert this to map?
You can convert to JSON using JSON Library (you must to attach JAR file in your project). Also, I found a good answer for convert JSON to Map in this link. I recommended to use these functions.
Example:
JSONObject json = new JSONObject(<your_json_string>);
ArrayList issues = (ArrayList) jsonToMap(json).get("issues");
Each element in the ArrayList issues, it's already HashMap. For example, if you want to get date of no1, you could access of this way:
((HashMap)issues.get(0)).get("date")

mongodb find and return id as a string - java

Morning,
Seem to be having a brainfart! Have had a look around and can't see any one else having the same issue so I've either completely missed something (most likely) or nobody else has this use case.
I basically want to return all objects stored in a mongodb collection, including their id's, however as the string representation rather than the full object. So this:
public ArrayList findAllObjects(){
return db.getCollection("objects").find().into(new ArrayList<Document>());
}
{
_id: {
class: "org.bson.types.ObjectId",
counter: 7230903,
date: "2016-10-03T12:39:38Z",
machineIdentifier: 5652488,
processIdentifier: 8859,
time: 1475498378000,
timeSecond: 1475498378,
timestamp: 1475498378
},
name: "Test Object"
},
Now if I run a find on the mongo console I get something along the lines of:
{
"_id": ObjectId("57f2518a564008229b6e55b7"),
"name": "Test Object"
}
It's this 57f2518a564008229b6e55b7 that I'd like to return in the original json as the _id (potentially could add under another name) field.
I can get that string representation in the java code simply by running get getObjectId() on an individual document. So I could possibly loop through every result and set/add the _id but that feels like a bit of a smell to me.
Any suggestions would be welcome.
Thanks
Update:
Thanks Sinclair for the comments, I don't believe this is a duplicate though, as I do actually want to include the id not necessarily exclude anything. If the string representation was in the org.bson.types.ObjectId object as a property I could then potentially exclude the rest but that isn't the case.
You can convert the object to string simply using the toString() method:
List<Document> documents = collection.find().into(new ArrayList<>());
documents.parallelStream().forEach(document -> {
document.put("_id", document.get("_id").toString());
});

How to convert Invalid JSON String to JSONObject in Java?

I have a string response like below which is a invalid json as it contains "obj13=".I want to convert it to a JSONObject(JAVA) and use it.Is there any good way to convert it to JSONObject without using String split operation.
obj13={
players: [
{
name: "rocky",
place: "brazil",
age: "21",
},
{
name: "andy",
place: "New Zealand",
age: "23",
}
]
}
This is, of course, JavaScript, not JSON. If you can, I would go back to the service provider and ask for a JSON response.
If the format of the string is consistent, you could just use:
json=json.substring(json.indexof('=')+1);
and then parse the result. Note that most good parsers should have an option to allow the keywords without quotes and to allow the extraneous commas (mine does, but unfortunately for you it doesn't create JSONObject's but is of a lower level - it's designed to construct the data-structure of the caller's choice, which could be a JSONObject if that's what you wanted but you'd have to code it).
If the result may or may not have the assignment, you may want to get a bit fancier and ensure that the non-whitespace characters before the '=' are valid for a JS identifier and the first non-whitespace after it is '{'.

Categories