Remove key from a Json inside a JsonObject

If Gson is like Jackson (I assume so) you'll have to first get the JsonObject "accounts" from the root object and then remove the member "email", e.g. like this:

jsonObj.getAsJsonObject("accounts").remove("email");

Alternatively - and probably the preferred way - you would map the json object to a POJO (one that has the fields "status", "accounts" and "accounts" would point to another POJO), navigate to the accounts-POJO and set "email" to null there. Then you reformat the root POJO to JSON and apply a setting that omits fields with null values.

Edit (answer to the question in the comment):

To make it short, I don't know whether there is a built-in functionality or not but it should be doable.

The problem is that if you just provide keys like email etc. you might get situations where there are multiple keys so identifying the correct one could be hard. Thus it might be better to provide the key as accounts.email and split the "key" into sub-expressions and then traverse the Json tree using the parts or convert the Json to a POJO and use some expression language (e.g. Java EL or OGNL) to traverse the POJO.

If you want to remove all properties named email you could just travers the entire json tree, check whether there is a property with that name and if so remove it.


Alternatively, you can use below:

DocumentContext doc = JsonPath.parse(json);
doc.delete(jsonPath);

Where json and and jsonPath are strings.

Library: com.jayway.jsonpath.DocumentContext.

Tags:

Java

Json