Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have JsonObject like below

{"status":"ACTIVE","accounts":{"email":"[email protected]","name":"Test"}}

How can I remove Json key "email" and its value from the JsonObject by using something like jsonObj.remove("email") in java

JsonObj.removev working for me if I need to remove status key jsonObj.remove("status")

Update

Some more background, This is for mainly testing a rest end point. In my test I created java object matching to payload with Builder pattern and then covert to Json using GsonBuilder like

import com.google.gson.GsonBuilder;
import com.google.gson.JsonObject;
public class JsonConvertor() {
public static JsonObject convertToJsonObject(Object payload) {
GsonBuilder builder = new GsonBuilder();
return (JsonObject) builder.setFieldNamingPolicy(FieldNamingPolicy.Policy).
            create().toJsonTree(payload);
}}

If I need to remove a required field I use, JsonObj.remove("key") on Json Object created by above function.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
451 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...