How to check the if statement value in drools using dialect "Mvel"? - java

I have a json below
"root":[
{
"refDataId": 1,
"children": [
{
"refDataId": 20
},
{
"refDataId": 99,
"otherValue": "Facility"
}
]
},
{
"refDataId": 2,
"children": [
{
"refDataId": 30
},
{
"refDataId": 99,
"otherValue": "Officer"
}
]
}
]
How to check the value above using the if statement in rule drools?
I edited the question. This is for drools rule
For example my rules is:
rule "test"
when
RuleEngine(inputObject!.adultHealth!.children contains 99)
then
info("children contains value 99");
end
And how to check the value of "refDataId": 99, and "otherValue": "Officer"?
If the value has to get from 2nd child json "refDataId": 2,

You can extract data using any json parser
I have used org.json
The following code tries to find an OFFICER from your json data.
JSONObject obj = new JSONObject(jsonString);
JSONArray objArray = obj.optJSONArray("root");
for (Object jo : objArray) {
JSONObject arrayElement = new JSONObject(jo.toString());
JSONArray childrenArray = arrayElement.getJSONArray("children");
for (Object child : childrenArray) {
JSONObject childJo = new JSONObject(child.toString());
if (Integer.parseInt(childJo.get("refDataId").toString()) == 99) {
if (childJo.get("otherValue").toString().equals("Officer")) {
System.out.println("Success Officer Found !");
}
}
}
}

Looking here Nested JSON iterations using drools Fluent API it seems to me it is enough to create data objects corresponding to structure of your JSON.

Related

Update Json value in json Array in Java

{
"page": {
"size": 2,
"number": 2
},
"places": [
{
"eventName": "XYZ",
"createdByUser": "xyz#xyz.com",
"modifiedDateTime": "2021-03-31T09:59:48.616Z",
"modifiedByUser": "xyz#xyz.com"
}
]}
I am trying to update the "eventName" field with new String. I tried with the following code, It updates the field but returns only four fields in the json array.
public String modifyJson() throws Exception{
String jsonString = PiplineJson.payload(PiplineJson.filePath());
System.out.println(jsonString);
JSONObject jobject = new JSONObject(jsonString);
String uu = jobject.getJSONArray("places")
.getJSONObject(0)
.put("eventName", randomString())
.toString();
System.out.println(uu);
return uu;
}
This is what the above code does.
{
"eventName": "ABCD",
"createdByUser": "xyz#xyz.com",
"modifiedDateTime": "2021-03-31T09:59:48.616Z",
"modifiedByUser": "xyz#xyz.com"
}
I am trying to get the complete json once it updates the eventName filed.
{
"page": {
"size": 2,
"number": 2
},
"places": [
{
"eventName": "ABCD",
"createdByUser": "xyz#xyz.com",
"modifiedDateTime": "2021-03-31T09:59:48.616Z",
"modifiedByUser": "xyz#xyz.com"
}
]}
The problem is the way that you are chaining the operations together. The problem is that you are calling toString() on the result of the put call. The put calls returns the inner JSONObject that it was called on. So you end up serializing the wrong object.
Changing this:
String uu = jobject.getJSONArray("places")
.getJSONObject(0)
.put("eventName", randomString())
.toString();
to
jobject.getJSONArray("places")
.getJSONObject(0)
.put("eventName", randomString());
String uu = jobject.toString();
should work.
That's because you are returning the first element you extracted from "places" array. You should return "jobject.toString()" instead.

Create a brand new type of searchable tree in JSON for Java

I am thinking of a new way to extract data from JSON. The following example is what I want:
Look for a key and value pair and give me that object.
Inside that object, give me the value to this key.
I want to get the power of knighthero in the following JSON, by telling it to find the username knighthero. This is really difficult, and I've tried JSONArray and JSONObject, but can't figure it out. I know the length is 3, but now what?
{
"data": [
{
"power": 75,
"registrant": {
"group": "elf",
"username": "kevin23"
}
},
{
"power": 34,
"registrant": {
"group": "fairy",
"username": "msi56"
}
},
{
"power": 150,
"registrant": {
"group": "orc",
"username": "knighthero"
}
}
]
}
I have tried JsonPath and all I get is [] when I print the string. I have tried JSONArray, but can't figure out how to do it.
With org.json librairy and your json described.
JSONObject jo0 = new JSONObject("{\"data\": ["
+ "{\"power\": 75,"
+ "\"registrant\": {\"group\": \"elf\",\"username\": \"kevin23\"}},"
+ "{\"power\": 34,"
+ "\"registrant\": {\"group\": \"fairy\",\"username\": \"msi56\"}},"
+ "{\"power\": 150,"
+ "\"registrant\": {\"group\": \"orc\",\"username\": \"knighthero\"}}"
+ "]}");
JSONArray ja = jo0.getJSONArray("data");
for(int i=0;i<ja.length();i++){
if(ja.getJSONObject(i).getJSONObject("registrant").getString("username").equals("knighthero")){
System.out.println(ja.getJSONObject(i).getInt("power"));
break;
}
}
EDIT
My bad, I make a mistake, here the good version

how to get elements from JSONObject and write it to file

i have a following JSONObject
{"elements": [
{
"name": "StartLabelFormat",
"value": "^XA"
},
{
"name": "shipperAddressLine1",
"value": "Street1",
"format": {"Text": {
"orientation": "N",
"height": "28",
"width": 20,
"fontname": 0,
"y": 373,
"x": 20
}}
},
{
"name": "EndLabelFormat",
"value": "^XZ"
}
]}
Now i want to get element from this Object and write it to a file.
For Example, for this block
{
"name": "shipperAddressLine1",
"value": "Street1",
"format": {"Text": {
"orientation": "N",
"height": "28",
"width": 21,
"fontname": 0,
"y": 373,
"x": 20
}}
},
I want to write in file as
^FT 20, 373 ^A0N, 28, 21 ^FDStreet1^FS.
Please help me to do this.
How to do it ?
If you meet {} in your code , you can use JSONObject to parse it .
If you meet [] in your code , you can use JSONArray to parse it .
And if you meet [] in your code , you can use for loop to get value in it .
And you should use try catch in your code .
Try this in your code .
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray elements = jsonObject.getJSONArray("elements");
for (int i = 0; i < elements.length(); i++) {
JSONObject jsonObject1 = elements.getJSONObject(i);
String name = jsonObject1.optString("name");
String value = jsonObject1.optString("value");
JSONObject format = jsonObject1.optJSONObject("format");
JSONObject Text = format.optJSONObject("Text");
String orientation = Text.optString("orientation");
String height = Text.optString("height");
String width = Text.optString("width");
}
} catch (JSONException e) {
e.printStackTrace();
}
Note
And use optString and optJSONObject in your code . If format is null ,it will not return error .
And you can judge that JSONArray's length is not 0 and not null in the code .
To get this element from JsonArray
JsonObject yourElement = yourJsonArray.get(index);
Simply, you can use gson library for parsing json to objects.
public class Staff {
private String name;
private String value;
//...
and use Gson
String jsonInString = " {
"name": "shipperAddressLine1",
"value": "Street1"
}";
Staff staff = gson.fromJson(yourElement.toString() , Staff.class);
After that you can write in file by using your custom toString() method inside Staff class.
P.S. to convert JsonObject to String you can use also toString() method.

updating json value of a nested json array in a json file | Java

I have this below json content in a file.
[
{
"prjId": 1,
"name" : "ABC",
"issueCounter": 7,
"issue": [
{
"id": 1,
"status" : "Closed",
"comment" : "blah blah blah",
"loggedBy": "shdkjdlsj"
},
{
"id": 2,
"status" : "Open",
"comment": "nothing",
"loggedBy": "xyz"
}
]
},
{
"prjId": 2,
"name" : "XYZ",
"issueCounter": 7,
"issue": [
{
"id": 3,
"status" : "Closed",
"comment": "jjjjjjjj",
"loggedBy": "klwm"
},
{
"id": 4,
"status" : "Closed",
"comment": "test test test",
"loggedBy": "NACK"
}
]
}]
I am able to parse this file and then traverse this json to get to the node where i wish to update. Upon reaching that point, i am confused on how to update it so that it would reflect on file on filesystem.
JSONParser parser = new JSONParser();
JSONArray rootArray = (JSONArray) parser.parse(new FileReader(pathToFile+fileName));
JSONObject project=null;
for (Object rootEntry : rootArray)
{
project = (JSONObject) rootEntry;
if( 1 == (Long) project.get("prjId"))
{
JSONArray issueArray = (JSONArray) project.get("issue");
for (Object issueEntry : issueArray)
{
JSONObject issue = (JSONObject) issueEntry;
System.out.println((Long) issue.get("id"));
if(2==(Long) issue.get("id"))
{
//now update the "comment" attribute here.
System.out.println("updated the comment: "+trckParam.getComment());
}
}
}
I have just the json reader till this point so do I construct a String as-and-when I traverse the nodes and when i reach the point I need to update, I update it (and construct the remainder of the nodes in this json object, (not to break from the loop)) and then write the entire reconstructed string to same file? Or is there a better approach where I can traverse the JSONObject and once i update it, push the entire object onto a file without constructing a String of entire file.
I still need to figure out a way to take either of the approach. So any pointers or direction will be greatly helpful.

read json file and parse inner json array in java

{
"vers": 0.01,
"config": {
"rate": "perhr",
"valueColumns": [
"vCPU",
"ECU",
"memoryGiB",
"storageGB",
"linux"
],
"currencies": [
"USD"
],
"regions": [
{
"region": "us-east",
"instanceTypes": [
{
"type": "generalCurrentGen",
"sizes": [
{
"size": "t2.micro",
"vCPU": "1",
"ECU": "variable",
"memoryGiB": "1",
"storageGB": "ebsonly",
"valueColumns": [
{
"name": "linux",
"prices": {
"USD": "0.013"
}
}
]
},
{
"size": "t2.small",
"vCPU": "1",
"ECU": "variable",
"memoryGiB": "2",
"storageGB": "ebsonly",
"valueColumns": [
{
"name": "linux",
"prices": {
"USD": "0.026"
}
}
]
}
]
}
]
}
]
}
}
Hi, i wanted to read this json file. I tried various ways from google but getting a null at valuesColumns. I have to read sizes array and have to put in list.
I think it will help your cause if you format your json. As it is it's quite hard to read. Googling for a JSON beautifier quickly found me this one.
When working with JSON your browser console provides a nice environment for inspecting and playing with the data. I pasted it into the browser console and did (hit enter after each line):
var x = { ... paste JSON here ... }
x
x.config
x.config.valueColumns
This tells me that x is a JSON object, config is a JSON object and valueColumns is a JSON array
Now to java. Grab yourself a json library, and accessing valueColumns will be something like:
JSONObject x = new JSONObject("{ ... JSON string ... }");
JSONObject config = x.getJSONObject("config");
JSONArray valueColumns = config.getJSONArray("valueColumns");
You can then iterate over valueColumns and pull out what you need.
Note that the above only gets you to the first valueColumns array under config. By following the same principle you can go deeper into the structure and get out the valueColumns for the objects in the sizes array if that's what you're really after.
For parsing json to java there are simple step.
Below code snippet may help you.
// parse json to java
Object obj = parser.parse(s);
JSONObject json = (JSONObject) obj;
JSONObject o = (JSONObject) json.get("config");
//get json array.
JSONArray array = (JSONArray) o.get("valueColumns");
System.out.println(array.toJSONString());
//access element by index
System.out.println(array.get(0));

Categories