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.

Answer from Thomas on Stack Overflow
Top answer
1 of 3
50

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.

2 of 3
4

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.

🌐
Tabnine
tabnine.com › home page › code › java › org.json.jsonobject
org.json.JSONObject.remove java code examples | Tabnine
*/ public JSONObject put(String key, Object value) throws JSONException { if (key == null) { throw new NullPointerException("Null key."); } if (value != null) { testValidity(value); this.map.put(key, value); } else { this.remove(key); } return this; } ... /** * Remove an object from the internal JSONObject * @param key the key of the object */ public void remove(String key){ this.json.remove(key); if (this.parent != null && this.credential.isPersistent()) this.parent.commit(); }
🌐
GitHub
gist.github.com › gkhays › 4fe1e6193e62b1f2cad3bd4b00f16c92
Remove an attribute or element from a JSON array during enumeration · GitHub
July 18, 2018 - I ended up copying the JSON array into a Java collection and used the JSONObject.names() method to obtain a JSONArray of keys. JSONArray nameArray = firstJSON.names(); List<String> keyList = new ArrayList<String>(); for (int i = 0; i < nameArray.length(); i++) { keyList.add(nameArray.get(i).toString()); } for (int i = 0; i < ja.length(); i++) { for (String key : keyList) { JSONObject json = ja.getJSONObject(i); if (json.getString(key).equals("null")) { json.remove(key); } } }
🌐
Tabnine
tabnine.com › home page › code › java › org.json.simple.jsonobject
org.json.simple.JSONObject.remove java code examples | Tabnine
@Override public JSONObject joinMessages(Map<String, Tuple> streamMessageMap, MessageGetStrategy messageGetStrategy) { JSONObject message = new JSONObject(); for (String key : streamMessageMap.keySet()) { Tuple tuple = streamMessageMap.get(key); JSONObject obj = (JSONObject) messageGetStrategy.get(tuple); message.putAll(obj); } List<Object> emptyKeys = new ArrayList<>(); for(Object key : message.keySet()) { Object value = message.get(key); if(value == null || value.toString().length() == 0) { emptyKeys.add(key); } } for(Object o : emptyKeys) { message.remove(o); } message.put(getClass().getSim
🌐
CodingTechRoom
codingtechroom.com › question › -remove-nested-key-json-java
How to Remove a Nested Key from a JSON Object in Java - CodingTechRoom
Removing a nested key from a JSON object in Java involves traversing the structure and identifying the correct key to delete.
🌐
Restack
restack.io › p › json-utilities-knowledge-remove-keys-cat-ai
Remove Keys From Json Object In Java | Restackio
To effectively remove multiple entries from a JSON object in Java, you can utilize the remove method provided by the JSONObject class. This method allows you to specify the key you wish to remove, and it can be executed within a loop to handle multiple keys efficiently.
🌐
Coderanch
coderanch.com › t › 638379 › java › remove-part-code-dynamically-JSON
How to remove some part of code dynamically in JSON? (Java in General forum at Coderanch)
August 21, 2014 - programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums · this forum made possible by our volunteer staff, including ... ... I am dynamically producing a JSON as shown below with a Map Data Currently this is producing the following JSON But i need to create the following JSON Every comma seperated value inside the Map autoincrements the T level Map<String, List<String>> consilatedMapMap = new LinkedHashMap<String, List<String>>(); List<String> values = new LinkedList<String>(); values.add("Bummy Chips,Masala Roasted with peanuts(49)"); values.add("Bummy Chips,Nimbu filled(50)"); consilatedMapMap.put("Chips & Chocolates", values); This is my whole program As it is in the same level i want to remove
Find elsewhere
🌐
TutorialsPoint
tutorialspoint.com › how-to-remove-a-specific-element-from-a-json-array-in-java
How to remove a specific element from a JSON Array in Java?
You can remove an element from the JSONArray object using the remove() method. This method accepts an integer and removes the element in that particular index. import org.json.JSONArray; public class RemoveFromJsonArray { public static void main(String args[]) throws Exception { String [] myArray ...
🌐
Baeldung
baeldung.com › home › json › jackson › removing json elements with jackson
Removing JSON Elements With Jackson | Baeldung
January 8, 2024 - To remove an element by key, we’d follow these steps: Parse the JSON string or input stream using the Jackson ObjectMapper ... We’d like to remove the age property from this object.
🌐
Java Code Geeks
examples.javacodegeeks.com › home › java development › core java
Jackson: Remove JSON Elements - Java Code Geeks
September 6, 2023 - Removing elements from a JSON structure using the Jackson library is fundamental when working with JSON data in Java. Jackson provides a powerful and flexible set of tools for parsing, manipulating, and serializing JSON data. In this guide, we will explore various techniques and methods offered by Jackson to remove elements, keys, or properties from JSON objects and arrays.
🌐
WeWeb Community
community.weweb.io › ask us anything › how do i?
How to "remove" a key/value in a JSON object? - How do I? - WeWeb Community
April 15, 2024 - We can reset an entire variable but not a path. (reset variable value) We can update a path but not delete. I can set null, but that’s not the same thing. (change variable value). Setting to null will add bloat to my JSON unecessarily. So how do I delete the key in a nested JSON object variable?