简体   繁体   中英

How to return json object having particular value in java?

This is what I have as a json and I have one condition here to ignore the object which has object_name:[parent],I had tried somthing which didnt worked out can someone help me with the same

    [
  {
    "object_group": "Trans",
    "permission_values": [
      {
        "object_type": "Trans",
        "permission_type": [
          {
            "View": true
          }
        ],
        "object_name": [
          "Invoice"
        ]
      },
      {
        "object_type": "Trans",
        "permission_type": [
          {
            "View": true
          }
        ],
        "object_name": [
          "parent"
        ]
      }
    ]
  },
  {
    "object_group": "General",
    "permission_values": [
      {
        "object_type": "General",
        "permission_type": [
          {
            "View": true
          }
        ],
        "object_name": [
          "Customer"
        ]
      },
      {
        "object_type": "General",
        "permission_type": [
          {
            "Delete": true
          }
        ],
        "object_name": [
          "Product"
        ]
      }
    ]
  }
]

This is the actual Thing I tried which I got as from one I have one condition here to ignore the object which has object_name:[parent]

 import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.json.JSONArray;
import org.json.JSONObject;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

public class TestData {

    public static void main(String[] args) throws JsonMappingException, JsonProcessingException {

         String input = "{\"JSON_OBJECT\":[{\"object_type\":\"Trans\",\"permission_type\":[{\"View\":true}],\"object_name\":[\"Invoice\"]},{\"object_type\":\"General\",\"permission_type\":[{\"View\":true}],\"object_name\":[\"Customer\"]},{\"object_type\":\"Trans\",\"permission_type\":[{\"View\":true}],\"object_name\":[\"Payments\"]},{\"object_type\":\"General\",\"permission_type\":[{\"Delete\":true}],\"object_name\":[\"Product\"]}]}";
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode jsonNode = objectMapper.readTree(input);
            Iterator<JsonNode> jsonObject = jsonNode.get("JSON_OBJECT").iterator();
            ObjectNode objectNode = objectMapper.createObjectNode();

            while (jsonObject.hasNext()) {
                JsonNode node = jsonObject.next();
                String object_type = node.path("object_type").asText();
                if (objectNode.has(object_type)) {
                    JsonNode objectTypeNode = objectNode.get(object_type);
                    JsonNode permission_values = objectTypeNode.path("permission_values");
                    if (!permission_values.isMissingNode()) {
                        ObjectNode permissionNode = objectMapper.createObjectNode();
                        node.fields().forEachRemaining(kv -> permissionNode.set(kv.getKey(),kv.getValue()));
                        ((ArrayNode) permission_values).add(permissionNode);
                    } else {
                        ObjectNode permissionNode = objectMapper.createObjectNode();
                        node.fields().forEachRemaining(kv -> permissionNode.set(kv.getKey(),kv.getValue()));
                        ((ArrayNode) permission_values).add(permissionNode);
                    }
                } else {
                    ArrayNode permissionArrayNode = objectMapper.createArrayNode();
                    ObjectNode permissionNode = objectMapper.createObjectNode();
                    node.fields().forEachRemaining(kv -> permissionNode.set(kv.getKey(),kv.getValue()));
                    permissionArrayNode.add(permissionNode);
                    ObjectNode permNode = objectMapper.createObjectNode();
                    permNode.set("permission_values", permissionArrayNode);
                    objectNode.set(object_type, permNode);
                }
            }
            ArrayNode arrayNode = objectMapper.createArrayNode();
            objectNode.fieldNames().forEachRemaining(key ->{
                ObjectNode node = objectMapper.createObjectNode();
                node.put("object_group",key);
                objectNode.get(key).fields().forEachRemaining(kv -> node.set(kv.getKey(),kv.getValue()));
                arrayNode.add(node);
            });
            System.out.println(arrayNode.toString());
    }
}

Expected output:- can someone pls help me to get this output..

[
  {
    "object_group": "Trans",
    "permission_values": [
      {
        "permission_type": [
          {
            "View": true
          }
        ],
        "object_name": [
          "Invoice"
        ]
      }
    ]
  },
  {
    "object_group": "General",
    "permission_values": [
      {
        "permission_type": [
          {
            "View": true
          }
        ],
        "object_name": [
          "Customer"
        ]
      },
      {
        "permission_type": [
          {
            "Delete": true
          }
        ],
        "object_name": [
          "Product"
        ]
      }
    ]
  }
]

I think your approach is a bit fundamentally wrong, it would be better if you utilize gson library to get Objects which you can easily get the required values from once initiated.

I recommend using this tool to easily get POJO object in gson notation as well.

example generated three classes from the tool:

-----------------------------------com.example.JsonObject.java-----------------------------------

package com.example;

import java.util.List;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

@Generated("jsonschema2pojo")
public class JsonObject {

@SerializedName("object_type")
@Expose
private String objectType;
@SerializedName("permission_type")
@Expose
private List<PermissionType> permissionType = null;
@SerializedName("object_name")
@Expose
private List<String> objectName = null;

public String getObjectType() {
return objectType;
}

public void setObjectType(String objectType) {
this.objectType = objectType;
}

public List<PermissionType> getPermissionType() {
return permissionType;
}

public void setPermissionType(List<PermissionType> permissionType) {
this.permissionType = permissionType;
}

public List<String> getObjectName() {
return objectName;
}

public void setObjectName(List<String> objectName) {
this.objectName = objectName;
}

}
-----------------------------------com.example.MyClass.java-----------------------------------

package com.example;

import java.util.List;
import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

@Generated("jsonschema2pojo")
public class MyClass {

@SerializedName("JSON_OBJECT")
@Expose
private List<JsonObject> jsonObject = null;

public List<JsonObject> getJsonObject() {
return jsonObject;
}

public void setJsonObject(List<JsonObject> jsonObject) {
this.jsonObject = jsonObject;
}

}

-----------------------------------com.example.PermissionType.java-----------------------------------

package com.example;

import javax.annotation.Generated;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

@Generated("jsonschema2pojo")
public class PermissionType {

@SerializedName("View")
@Expose
private Boolean view;
@SerializedName("Delete")
@Expose
private Boolean delete;

public Boolean getView() {
return view;
}

public void setView(Boolean view) {
this.view = view;
}

public Boolean getDelete() {
return delete;
}

public void setDelete(Boolean delete) {
this.delete = delete;
}

}

So when you fetch the response array from your REST/Api methods, you could simply do something like:

...
..
.
JSONObject responseObject = resObj.getJSONObject("whole_response_api");

     
     Type listType = new TypeToken<MyClass>() {
     }.getType();
     MyClass javaObject = gson.fromJson(responseObject.toString(), listType));

     String objectTypeOf1st = javaObject.getJsonObject(1).getObjectType();

...
..
.

NOTE: Did not compile this, so syntax could we way-off, but I hope you understood my point though.

EDIT: This video by CodingInFlow explains the concept of De-serializing and serializing splendidly if you want to take a look.

If you don't want to create POJOs, you have to play with general json object or Map. I have used Jackson library to get the output. Please see If this is what you want. Since expected output is of not a proper json, I have modified to get below output.

    String input = "{\"JSON_OBJECT\":[{\"object_type\":\"Trans\",\"permission_type\":[{\"View\":true}],\"object_name\":[\"Invoice\"]},{\"object_type\":\"General\",\"permission_type\":[{\"View\":true}],\"object_name\":[\"Customer\"]},{\"object_type\":\"Trans\",\"permission_type\":[{\"View\":true}],\"object_name\":[\"Payments\"]},{\"object_type\":\"General\",\"permission_type\":[{\"Delete\":true}],\"object_name\":[\"Product\"]}]}";
    ObjectMapper objectMapper = new ObjectMapper();
    JsonNode jsonNode = objectMapper.readTree(input);
    Iterator<JsonNode> jsonObject = jsonNode.get("JSON_OBJECT").iterator();
    ObjectNode objectNode = objectMapper.createObjectNode();

                while (jsonObject.hasNext()) {
            JsonNode node = jsonObject.next();
            String object_type = node.path("object_type").asText();
            if (objectNode.has(object_type)) {
                JsonNode objectTypeNode = objectNode.get(object_type);
                JsonNode permission_values = objectTypeNode.path("permission_values");
                if (!permission_values.isMissingNode()) {
                    ObjectNode permissionNode = objectMapper.createObjectNode();
                    node.fields().forEachRemaining(kv -> addIfRequired(permissionNode, kv));
                    ((ArrayNode) permission_values).add(permissionNode);
                } else {
                    ObjectNode permissionNode = objectMapper.createObjectNode();
                    node.fields().forEachRemaining(kv -> addIfRequired(permissionNode, kv));
                    ((ArrayNode) permission_values).add(permissionNode);
                }
            } else {
                ArrayNode permissionArrayNode = objectMapper.createArrayNode();
                ObjectNode permissionNode = objectMapper.createObjectNode();
                node.fields().forEachRemaining(kv -> addIfRequired(permissionNode, kv));
                permissionArrayNode.add(permissionNode);
                ObjectNode permNode = objectMapper.createObjectNode();
                permNode.set("permission_values", permissionArrayNode);
                objectNode.set(object_type, permNode);
            }
        }

    System.out.println(objectNode.toString());

Edit 3

private static void addIfRequired(ObjectNode permissionNode, Map.Entry<String, JsonNode> kv) {
    if (!("object_name".equalsIgnoreCase(kv.getKey()) && kv.getValue().get(0).asText().toLowerCase().contains("parent"))) {
        permissionNode.set(kv.getKey(), kv.getValue());
    }
}

//output

{
  "Trans": {
    "permission_values": [
      {
        "permission_type": [
          {
            "View": true
          }
        ],
        "object_name": [
          "Invoice"
        ]
      },
      {
        "permission_type": [
          {
            "View": true
          }
        ],
        "object_name": [
          "Payments"
        ]
      }
    ]
  },
  "General": {
    "permission_values": [
      {
        "permission_type": [
          {
            "View": true
          }
        ],
        "object_name": [
          "Customer"
        ]
      },
      {
        "permission_type": [
          {
            "Delete": true
          }
        ],
        "object_name": [
          "Product"
        ]
      }
    ]
  }
}

Edit: Assuming you need array as output

    ArrayNode arrayNode = objectMapper.createArrayNode();
    objectNode.fieldNames().forEachRemaining(key ->{
        ObjectNode node = objectMapper.createObjectNode();
        node.put("object_group",key);
        objectNode.get(key).fields().forEachRemaining(kv -> node.set(kv.getKey(),kv.getValue()));
        arrayNode.add(node);
    });
    System.out.println(arrayNode.toString());

//output

[
  {
    "object_group": "Trans",
    "permission_values": [
      {
        "permission_type": [
          {
            "View": true
          }
        ],
        "object_name": [
          "Invoice"
        ]
      },
      {
        "permission_type": [
          {
            "View": true
          }
        ],
        "object_name": [
          "Payments"
        ]
      }
    ]
  },
  {
    "object_group": "General",
    "permission_values": [
      {
        "permission_type": [
          {
            "View": true
          }
        ],
        "object_name": [
          "Customer"
        ]
      },
      {
        "permission_type": [
          {
            "Delete": true
          }
        ],
        "object_name": [
          "Product"
        ]
      }
    ]
  }
]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM