Check if column exists in Nested JSON - java

Below is my sample JSON
{
"_id":{
"$oid":"1564t8re13e4ter86"
},
"object":{
"shop":"shop1",
"domain":"Divers",
"sell":[
{
"location":{
"zipCode":"58000",
"city":"NEVERS"
},
"properties":{
"description":"ddddd!!!!",
"id":"f1re67897116fre87"
},
"employee":[
{
"name":"employee1",
"id":"245975"
},
{
"name":"employee2",
"id":"458624"
}
],
"customer":{
"name":"Customer1",
"custid":"test_réf"
}
"preference":"talking"
}
]
}
}
In the above sample i would like to know if this particular column exists in the $.object.sell.preference exists , as in most cases it is not existing which is leading to failure.
Also i am good if there is any option i can set to get null or blank as return when using readcontext.read($...)
Thanks in Advance
Regards

NOTE: I'm referring in java
Yes, it is possible to check using jsonObject.has() method.
Suppose you have response variable in which you have full JSON
You can proceed it like this
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONObject("object").getJSONArray("sell");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
if (jsonObject1.has("preference")) {
// Exist
} else {
//Not Exist
}
}

try:
bool(json['object']['sell'][0]["preference"])
it will return false if empty and vice versa

Related

apply condition on json object with in json array java

I am fetching some json from server like this
"applications": [
{
"packageName": "com.facebook.mlite",
"defaultPermissionPolicy": "PROMPT",
"delegatedScopes": [
"DELEGATED_SCOPE_UNSPECIFIED",
"CERT_INSTALL",
"MANAGED_CONFIGURATIONS",
"BLOCK_UNINSTALL",
"PERMISSION_GRANT",
"PACKAGE_ACCESS",
"ENABLE_SYSTEM_APP"
],
"permissionGrants": [
{
"permission": "tt",
"policy": "PROMPT"
}
],
"disabled": false,
"minimumVersionCode": 0
},
{
"packageName": "com.facebook.mlite",
"defaultPermissionPolicy": "PROMPT",
"delegatedScopes": [
"DELEGATED_SCOPE_UNSPECIFIED",
"CERT_INSTALL",
"MANAGED_CONFIGURATIONS",
"BLOCK_UNINSTALL",
"PERMISSION_GRANT",
"PACKAGE_ACCESS",
"ENABLE_SYSTEM_APP"
],
"permissionGrants": [
{
"permission": "tt",
}
],
}
]
Now there is a json array "application":[] in which there are several json object. Now these object are not same. Some json objects are missing like first object contains installType but second one doesn't. Now i want to add this in a list for a recyclerview if a json object is missing i want to send empty tring in contrustor of my pojo class
public Application(String defaultPermissionPolicy, List<String> delegatedScopes, List<com.ariaware.enrolldevice.PolicyPojos.PermissionGrants> permissionGrants, Boolean disabled, String installType, Integer minimumVersionCode, String packageName) {
this.defaultPermissionPolicy = defaultPermissionPolicy;
this.delegatedScopes = delegatedScopes;
PermissionGrants = permissionGrants;
this.disabled = disabled;
this.installType = installType;
this.minimumVersionCode = minimumVersionCode;
this.packageName = packageName;
}
This is constructor of my class. Now how will i loop through json array and check either if an object exists or not or if doesn't exist then send empty string. I need to check every object
You could implement another constructor which accepts a JSONObject as a parameter and create the object. Inside the constructor use optString which returns an empty string if the field doesn't exist (also accepts another parameter for the fallback value).
public Application(JSONObject jsonObject) {
this.installType = jsonObject.optString("installType");
// example of an array
JSONArray scopes = jsonObject.optJSONArray("delegatedScopes");
this.delegatedScopes = new ArrayList<>();
for (int i = 0; i < scopes.length(); i++)
this.delegatedScopes.add(scopes.optString(i));
//other initialization...
}
Finally, you retrieve each JSONObject from the applications array.
try {
JSONArray res = data.optJSONArray("applications");
Application[] items = new Application[res.length()];
for (int i = 0; i < res.length(); i++)
items[i] = new Application(res.getJSONObject(i));
} catch (JSONException e) {
e.printStackTrace();
}

java/JSON not showing needed value from parsing JSON

Hey all I am trying to get the needed information from a JSON string.
This is what my JSON looks like:
{
"xmlns:jp": "http://jazz.net/xmlns/prod/jazz/process/1.0/",
"childNodes": [{
"childNodes": [{
"childNodes": ["https://zzzz.zzzz.zxzzxzxz:9443/qm/process/project-areas/_rutR33fwEee_eeo4ry7Vg/members/bob"],
"tagName": "jp06:url"
}, {
"childNodes": ["https://zzzz.zzzz.zxzzxzxz:9443/jts/users/bob"],
"tagName": "jp06:user-url"
}, {...etc.....
This is my java code:
JSONObject jsonObject = JSONML.toJSONObject(theReturnedResult);
JSONArray jsonArray1 = jsonObject.getJSONArray("childNodes");
JSONObject device = jsonArray1.getJSONObject(0);
JSONArray vendors = device.getJSONArray("childNodes");
List<String> result = new ArrayList<>();
vendors.forEach(o -> {
if (o instanceof JSONObject) {
JSONObject crt = (JSONObject) o;
String blah = crt.getString("tagName");
System.out.println(crt.getString("tagName"));
if (blah.equals("jp06:role-assignments-url")) {
String blah1 = crt.getString("tagName");
mapHash.put(owner, crt.getString("childNodes"));
} else if (crt.has("ns6:owner")) {
//See who's the owner of this TSR
owner = crt.getString("childNodes");
}
}
});
The String blah1 = crt.getString("tagName"); return the 2nd tagName but when it goes into the if/than then I can not seem to find it due to it telling me JSONObject["childNodes"] not a string.
I am trying to get the URL value that's assigned to the childNodes. So I am unsure as how the first String blah = crt.getString("tagName") works but when I try another one in the if/else statement it doesn't return the url - only an error below?
I am trying to get the value "https://zzzz.zzzz.zxzzxzxz:9443/qm/process/project-areas/_rutR33fwEee_eeo4ry7Vg/members/bob.
Help would be great!
The error is right isn't it ? childNodes is not a String but an array with a single string in it. So it should be :
mapHash.put(owner, crt.getJSONArray("childNodes").getString(0));

JSON array from JSON object is returning null

I want to read JSON array
"connectTo":[
{
"url": "wss://localhost/opt/siml"
}
],
from JSON string :
{
"cluster":{
"enabled":"true",
"clusterName":"cluster0",
"simlURL":"wss://localhost:5443/opt/siml"
},
"simlFieldWatchUrl":"fieldwatchholder.jsp",
"persistFolder":"clusterconfig/concentratorBPersist",
"sslCrtFile":"clusterconfig/certDirB/siml.crt",
"sslKeyFile":"clusterconfig/certDirB/siml.key",
"SIMLID":"TestServerB",
"localWebProxyServer":"localhost",
"localWebProxyPort":8080,
"SIMLProxyPort":8400,
"SIMLWebPort":8300,
"turnOnExtraSIMLWebSocket":"false",
"autoPromoteNewConnectionsFromPurgatory":true,
"connectTo":[
{
"url": "wss://localhost/opt/siml"
}
],
"tempLogins":[
{
"username":"root",
"password":"root"
}
]
}
My code to read url is:
JSONArray connectTo = (JSONArray) config.get("connectTo");
System.out.println("Connect to : " + connectTo);
for (Object o : connectTo) {
JSONObject connect = (JSONObject) o;
String url = (String) connect.get("url");
System.out.println(url);
}
But System.out.println("Connect to : " + connectTo); this is returning
Connect to : []
I read some old question but did not get satisfactory answer. Please Help. And thank you in advance :)
I just assume config is a JSONObject.
JSONArray connectTo = config.getJSONArray("connectTo");
config.get() returns an Object while config.getJSONArray() returns a JSONArray.
Try this:
JSONArray connectTo =config.getJSONArray("connectTo");
System.out.println("Connect to : " + connectTo);
for (int i=0;i<connectTo.length();i++)
{
JSONObject connect = connectTo.getJSONObject(i);
String url = connect.get("url");
System.out.println(url);
}
I got it working like this, not sure if this helps:
var json = {
"connectTo": [{
"url": "wss://localhost/opt/siml"
}]
};
for (var o = 0; o < json.connectTo.length; o++) {
console.log(json.connectTo[o].url);
}

json SELECT multiple value by key in java

I have one json like below given
[{
"D_Table_Name": "BUILDING",
"S_Table_Name": "View1",
"S_Data_Field_Name": "USECD",
"D_Field_Name": "Description",
"MappingCode": "FIELD"
},
{
"D_Table_Name": "BUILDING",
"S_Table_Name": "View1",
"S_Data_Field_Name": "USECD",
"D_Field_Name": "StndCode",
"MappingCode": "FIELD"
},
{
"D_Table_Name": "asdasd",
"S_Table_Name": "View1",
"S_Data_Field_Name": "qwew",
"D_Field_Name": "ijhbgr4",
"MappingCode": "FIELD"
},
{
"D_Table_Name": "qwsdcv",
"S_Table_Name": "View1",
"S_Data_Field_Name": "kjmnbv",
"D_Field_Name": "dszfs",
"MappingCode": "FIELD"
}]
how to get all value of the key S_Table_Name
Assuming you are using any particular library to convert JSON string into an Object, Let's say I am taking GSON library
List<String> sTableNameValues = new ArrayList<>();
List<Map<String,String>> input = new GSON.fromJSON(inputJSONString);
for(Map.Entry<String,String> entry: input.entrySet()){
if(entry.getKey().equals("S_Table_Name")){
sTableNameValues.add(entry.getValue());
}
}
// Now all your S_Table_Name values are inside your list.
Use jackson library:
ObjectMapper mapper = new ObjectMapper();
JsonNode array = mapper.readValue(yourJson, JsonNode.class);
Get values:
for (int i = 0; i < array.size(); i++) {
String reportKey = array.get(i).get("S_Table_Name").textValue();
System.out.println(reportKey);
}
Something like json-path should be of help. In your case, the expression should be something like:
$[*].S_Table_Name
You can also use org.json.JSONObject library. Please see below code for this :
String response = "[{\"D_Table_Name\": \"BUILDING\",\"S_Table_Name\": \"View1\",\"S_Data_Field_Name\": \"USECD\",\"D_Field_Name\": \"Description\",\"MappingCode\": \"FIELD\"},{\"D_Table_Name\": \"BUILDING\",\"S_Table_Name\": \"View1\",\"S_Data_Field_Name\": \"USECD\",\"D_Field_Name\": \"StndCode\",\"MappingCode\": \"FIELD\"},{\"D_Table_Name\": \"asdasd\",\t\t\"S_Table_Name\": \"View1\",\"S_Data_Field_Name\": \"qwew\",\"D_Field_Name\": \"ijhbgr4\",\"MappingCode\": \"FIELD\"},{\"D_Table_Name\": \"qwsdcv\",\"S_Table_Name\": \"View1\",\t\"S_Data_Field_Name\": \"kjmnbv\",\"D_Field_Name\": \"dszfs\",\"MappingCode\": \"FIELD\"}]";
JSONArray responseArray = new JSONArray(response);
if (responseArray.length() > 0) {
for (int i = 0; i < responseArray.length(); i++) {
JSONObject responseObject = responseArray.getJSONObject(i);
if (responseObject.has("S_Table_Name")) {
String S_Table_Name = responseObject.getString("S_Table_Name");
System.out.println(S_Table_Name);
}
}
}

Extract json subset with few attributes from the main json

Is there an API/tool available for extracting specific attributes(json subset) of a json in java, similar to apache-commons beanutils copy?
For example I have the following JSON
{
"fixed":[
{
"b":"some value",
"c":"some value",
"d":"some value",
"e":"some value",
"f":"some value"
},
{
"b":"value",
"c":"value",
"d":"value",
"e":"value",
"f":"value"
}
]
}
I would like to have the following json
{
"fixed":[
{
"b":"some value",
"e":"some value",
"f":"some value"
},
{
"b":"value",
"e":"value",
"f":"value"
}
]
}
I came up the following method, but not sure if its the right approach
public JSONObject parseJSON(JSONObject data,List<String> subset){
JSONArray fixedArray = (JSONArray) data.get("fixed");
JSONObject resObj = new JSONObject();
JSONArray resArray = new JSONArray();
for(int i=0;i<fixedArray.size();i++){
JSONObject element = (JSONObject) fixedArray.get(i);
JSONObject resElement = new JSONObject();
for(String s:subset){
resElement.put(s, element.get(s));
}
resArray.add(resElement);
}
return resObj.put("fixed", resArray);
}
I had a look at this SO question, but wasn't helpful for this topic.
https://docs.oracle.com/javase/tutorial/jaxb/intro/arch.html you can also create you own pojo class from JAXB ,if you want.

Categories