apply condition on json object with in json array java - 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();
}

Related

Nested JSONArray

I need to read a JSON file with following form:
{
"Data":[{
"foo":"22",
"bar":"33",
"array":[
{
"1foo":"22",
"1bar":"33"
},
{
"2foo":"22",
"2bar":"33",
}
],
"anotherData":{
"foofoo":"22",
"barbar":"33"
},
"some more data":"11",
"some more data":"11"
},
{and the cycle here starts again from -->
"foo":"22",
"bar":"33",
"array":[
My question stands : How do I access individual elements given it's sometimes JSONObject and sometimes JSONArray. I tried using org.json library but I'm failing to access anything after this line -> "array":[. I tried various combinations of JSONObject and JSONArray up to no avail.
My latest code looked something like this:
List<Data> data= new ArrayList<>();
String rawJson = getJsonAsString();
JSONObject outer = new JSONObject(rawJson);
JSONArray jArr= outer.getJSONArray("Data");
JSONObject inner= outer.getJSONObject("array");
for(int i =0; i<jArr.length(); i++){
JSONObject jsonEvent = jArr.getJSONObject(i);
String foo = jsonEvent.getString("foo"); <-- this works,
String 1foo = jsonEvent.getString("1foo"); <-- but this doesn't and i cant access it
I tried dozens of different solutions(tried myself and tried to find something here as well, but every case with those nested arrays is different and I can't add those solutions together to get answer for my case)
You can increase your readability if you beautify your raw JSON string:
{
"Data":[
{
"foo":"22",
"bar":"33",
"array":[
{
"1foo":"22",
"1bar":"33"
},
{
"2foo":"22",
"2bar":"33"
}
],
"anotherData":{
"foofoo":"22",
"barbar":"33"
},
"some more data":"11",
"some more data":"11"
},
{ and the cycle here starts again from -->
"foo":"22",
"bar":"33",
"array":[
...
],
...
}
]
}
So, stick to the following code:
JSONArray jArr = outer.getJSONArray("Data");
jArr is now filled with array of your Object.
And to loop through your Object array, you can use a for-loop which you have done it correctly.
for (int i = 0; i < jArr.length(); i++) {
// The below gets your Object
JSONObject jsonEvent = jArr.getJSONObject(i);
}
And now each jsonEvent contains your Object, which you can access the Object by their type.
For example, if you would like to access foo, you can use:
String foo = jsonEvent.getString("foo"); // foo = "22"
String bar = jsonEvent.getString("bar"); // bar = "33"
// Note that your array is another Array, you need to get it as JSONArray first
JSONArray arrayJson = jsonEvent.getJSONArray("array");
And as 1foo is in the first Object for your array, you need to access it like this:
JSONObject firstObjectInArray = arrayJson.getJSONObject(0);
String target = firstObjectInArray.getString("1foo"); // target = "22"
And to access foofoo, as it is an attribute of the JSON Object anotherData, so you should obtain anotherData as JSONObject first, and then you can access foofoo:
JSONObject anotherDataObject = jsonEvent.getJSONObject("anotherData");
String foofoo = anotherDataObject.getString("foofoo"); // foofoo = "22"
So the full code within your for-loop should look like this:
for (int i = 0; i < jArr.length(); i++) {
// The below gets your Object
JSONObject jsonEvent = jArr.getJSONObject(i);
String foo = jsonEvent.getString("foo");
JSONArray arrayJson = jsonEvent.getJSONArray("array");
String target = arrayJson.getJSONObject(0).getString("1foo");
// Add to get foofoo
JSONObject anotherDataObject = jsonEvent.getJSONObject("anotherData");
String foofoo = anotherDataObject.getString("foofoo");
}

Parse only particular fields in JSON at once

I have a huge JSON but I only need to parse specific fields. I know paths to these fields so I decided to try JPath and it works but I want to parse all fields at once.
Let's say I have such JSON:
{
"data": [
{
"field1": 1,
"field2": 1,
...
"another_data": [ {
"required_field1": "1",
"required_field2": "2"
}
],
...
}
]
}
I want to get only required fields with these paths and map it to Java POJO:
$.data[*].another_data[*].required_field1
$.data[*].another_data[*].required_field2
So as a final result I want to have a list of Java objects, where the object contains required_field1 and required_field2.
UPD:
how it works now
I have a Java POJO that's a container
class RequiredInfo {
private String field1;
private String field2;
//constructor, setters, etc
}
I read JSON path 2 times by using JPath:
String json = "...";
Object document = Configuration.defaultConfiguration().jsonProvider().parse(json);
List<String> reqFields1 = JsonPath.read(document, "$.data[*].another_data[*].required_field1");
List<String> reqFields2 = JsonPath.read(document, "$.data[*].another_data[*].required_field2")
and then I map it to my POJO
for (int i = 0; i < reqFields1.size(); i++) {
res.add(new RequiredInfo(reqFields1.get(i), reqFields2.get(i)));
}
bit I think there is a better way how I can do it
You can try by creating a JSON object and get data:
JSONObject yourJsonObject = (JSONObject) new JSONParser().parse(yourJson);
JSONObject data = (JSONObject) yourJsonObject.get("data");
JSONObject data0 = (JSONObject) data.get(0);
JSONObject another_data = (JSONObject) data0.get("another_data");
String required_field1 = another_data.get("required_field1").toString();
String required_field2 = another_data.get("required_field2").toString();
Now that you have values, you can add them in your POJOs.

Check if column exists in Nested JSON

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

Get Arraylist file json using java

I have problems with my code, I need to extract the "materias" markup in the arraylist. Example data:
[{
"name": "A114",
"grupo": "DAW2",
"tutor": 15,
"materias": ["DWES", "DWEC", "IW", "DAW", "IE"]
}]
I tried this, work but i need the content of the arraylist:
try { // this read the JSON file
line = new String(Files.readAllBytes(Paths.get("fileAulas")));
} catch (Exception ex) {
ex.printStackTrace();
}
JSONArray recs = new JSONArray(line);
for (Object rec : recs) {
Aula datos = new Aula();
JSONObject obj = ((JSONObject) rec);
String name = obj.getString("name");
//datos.setNombre(name);
String grupo = obj.getString("grupo");
//datos.setGrupo(grupo);
int tutor = obj.getInt("tutor");
//datos.setTutor(tutor);
}
My objetive is to read the arraylist and then datos.setArraylist to my another class. All works fine except read the arraylist
PD: I use java downloaded from Maven, to execute i use "javac -cp ./*: program.java"
materias is also an array, so you need something like:
JSONArray materias = obj.getJsonArray("materias");
List<String> materiasList = materias.getValuesAs(String.class);
This is not type-safe so you need to make sure the array will only have String values.
Also, if you are using Java 8, you can iterate over the values and store them manually (JsonArray is also a Collection<JsonValue>)
Quickly created short test implementation of your needs:
String json = "[{ \"name\":\"A114\",\"grupo\": \"DAW2\",\"tutor\":15,\"materias\": [\"DWES\",\"DWEC\",\"IW\",\"DAW\",\"IE\"]}]";
JSONArray objectArray = new JSONArray(json);
for (int x = 0; x < objectArray.length(); x++) {
JSONObject obj = objectArray.getJSONObject(x);
System.out.println("Name: " + obj.get("name"));
System.out.println("Grupo: " + obj.get("grupo"));
System.out.println("Tutor: " + obj.get("tutor"));
JSONArray materias = obj.getJSONArray("materias");
for (int y = 0; y < materias.length(); y++) {
System.out.println("Materia " + y + ": " + materias.get(y));
}
}
Output
Name: A114
Grupo: DAW2
Tutor: 15
Materia 0: DWES
Materia 1: DWEC
Materia 2: IW
Materia 3: DAW
Materia 4: IE
First gotta make your JSON Valid.
[{
"name": "A114",
"grupo": "DAW2",
"tutor": 15,
"materias": ["DWES", "DWEC", "IW", "DAW", "IE"]
}]
Secondly, you can try the following :
for (JsonElement rec : recs) {
Aula datos = new Aula();
JSONObject obj = rec.getAsJsonObject();
String name = obj.get("name").getAsString();
//datos.setNombre(name);
String grupo = obj.get("grupo").getAsString();
//datos.setGrupo(grupo);
int tutor = obj.get("tutor").getAsInt();
JsonObject obj = rec.getAsJsonObject();
JsonArray materias = obj.getAsJsonArray("materias");
List<String> materiasList = new ArrayList<>();
for (JsonElement item:
materias) {
materiasList.add(item.getAsString());
}
}
I believe that the syntax for an array in json is different that what you have in your file. For example - a simple complete json that contains an array of simple elements would be:
{"contacts":[
{ "firstName":"John", "lastName":"Doe" },
{ "firstName":"Jen", "lastName":"Smith" },
{ "firstName":"David", "lastName":"Jones" }
]}
In your text, you specify an array, without the opening and closing JSON '{' and '}'. Also, You would need to name the array element ("contacts" in the example above). I think that what you want would be (I used "arrayName" for the array element name):
{"arrayName":[{ "name":"A114","grupo": "DAW2","tutor":15,"materias":["DWES","DWEC","IW","DAW","IE"] },
{ "name":"121","grupo": "DAW1","tutor":8,"materias":["PROGRA","BD","SIS","LM","FOL"] },
{ "name":"A112","grupo": "AUTO1","tutor":5 },
{ "name":"A127","grupo": "ASIR1","tutor":2 },
{ "name":"A114","grupo": "SMR2","tutor":11 },
{ "name":"A128","grupo": "ASIR2","tutor":9,"materias":["IAW","ABD","ASIS","SI","IE"] },
{ "name":"A125","grupo": "ADM2","tutor":12 } ] }

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);
}
}
}

Categories