Java - Remove Fields from a JSON String recursively without POJOs

Viewed 7768

How do I remove some fields with a specified name from a JSON string recursively ?

For example, I want to remove the field "secondName" from the following JSON:

INPUT:

{
    "name" : "abc",
    "secondName": "qwe",
    "add" : "abcd",
    "moreDetails" : {
        "secondName": "qwe",
        "age" : "099"
    }
}

OUTPUT:

{
    "name" : "abc",
    "add" : "abcd",
    "moreDetails" : {
        "age" : "099"
    }
}

I have to remove some fields from a lot of different JSONs with different structures/schema, so I won't be able to deserialize/serialize to/from a POJO.

3 Answers

Gson deserializes any valid Json to LinkedTreeMap, like:

LinkedTreeMap<?,?> ltm = new Gson().fromJson(YOUR_JSON, LinkedTreeMap.class);

Then it is just about making some recursive methods to do the clean up:

public void alterEntry(Entry<?, ?> e) {
    if(e.getValue() instanceof Map) {
        alterMap((Map<?, ?>) e.getValue());
    } else {
        if(e.getKey().equals("secondName")) { // hard coded but you see the point 
            e.setValue(null); // we could remove the whole entry from the map
                              // but it makes thing more complicated. Setting null
                              // achieves the same.
        }
    }
}

public void alterMap(Map<?,?> map) {
    map.entrySet().forEach(this::alterEntry);
}

Usage:

alterMap(ltm);

You could try storing the JSON as a JSONObject, iterate over the keys using jsonObject.names() and remove the entries using jsonObject.remove(key).

You can do like below if you know the schema and heirarchy:

JsonObject jsonObj= gson.fromJson(json, JsonObject.class); jsonObj.getAsJsonObject("moreDetails").remove("secondName"); System.out.println(jsonObj.getAsString());

refer this for more info Remove key from a Json inside a JsonObject

else you need to write a dynamic function which will check each and every element of JSON object and try to find the secondName element in it and remove it.

So consider here as you have multiple nested objects then you need to write a function which will iterate over each element and check its type if its again a jsonObject call the same method recursively or iteratively to check against current element, in each check you need to also verify that the key, if it matches with the key which has to be removed then you can remove it and continue the same.

for a hint on how to check a value type of JSON see this How to check the type of a value from a JSONObject?

Related