As it mentioned in comments above, you cant remove fields of compiled class at runtime. Assuming you have to exclude some field from generated json, there I see two options:

  1. Create a class with fields you want to be present in resulting json, copy required values from original object to a new created. This approach is called view model and allows you to decorate some object's data, hiding sensitive data from being exposed.
  2. Depending on implementation of your serializer there may be annotations to exclude fields. @JsonIgnore may be placed on getter method, if you are using Jackson (default in spring boot). Second aproach requires significant less code, but the first one is more flexible.
Answer from Aeteros on Stack Overflow
🌐
Stack Overflow
stackoverflow.com › questions › 71208288 › how-to-remove-a-field-from-pojo
java - How to remove a field from POJO - Stack Overflow
February 21, 2022 - If you had to use it without annotations, and cannot add a custom serializer you should map the User class into a more specific class without the field in question and then serialize that one. ... Not possible. The pojo can’t be modified.
🌐
Google Groups
groups.google.com › g › google-appengine › c › zpRS9Nd-rkQ
How to remove property of java object(POJO) with safty?
November 24, 2009 - ... Either email addresses are ... entities. That is, if you still need to read from a property but no longer need to write from it, simply leave the property field ......
Discussions

apex - Remove field from object list in class - Salesforce Stack Exchange
I have list of accounts and want to use them for post request. How can I remove unnecessary fields like id to set that list in setbody? Now I am just using for loop and json serialize. Some code. S... More on salesforce.stackexchange.com
🌐 salesforce.stackexchange.com
Spring JSON - Ignore if your POJO field has no corresponding field in said JSON
If you're using jackson, you can disable this. objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) https://www.baeldung.com/jackson-deserialize-json-unknown-properties More on reddit.com
🌐 r/javahelp
6
4
June 11, 2021
java - Want to hide some fields of an object that are being mapped to JSON by Jackson - Stack Overflow
If you don't want to put annotations on your Pojos you can also use Genson. Here is how you can exclude a field with it without any annotations (you can also use annotations if you want, but you have the choice). More on stackoverflow.com
🌐 stackoverflow.com
json - Dynamically add or remove a member variable of a class - Salesforce Stack Exchange
Apex doesn't let you modify class ... to, say, Javascript). Depending on what precisely you're trying to do, using a Map instead of a class may work. ... I am serialzing it. It is a requirement of the client. ... Not sure I understand your question completely, are you serializing an instance of this class, and do not want the Number_Address__c in the JSON? If so, look at serialize(objectToSerialize, suppressApexObjectNulls) ... I would like only that particular field to not exist, ... More on salesforce.stackexchange.com
🌐 salesforce.stackexchange.com
🌐
Stack Exchange
salesforce.stackexchange.com › questions › 354389 › remove-field-from-object-list-in-class
apex - Remove field from object list in class - Salesforce Stack Exchange
Map<String, Object> fields = acc.getPopulatedFieldsAsMap(); fields.remove('Id'); // etc request.setBody(JSON.serialize(fields));
🌐
Reddit
reddit.com › r/javahelp › spring json - ignore if your pojo field has no corresponding field in said json
r/javahelp on Reddit: Spring JSON - Ignore if your POJO field has no corresponding field in said JSON
June 11, 2021 -

We have a generic server response that is an absolutely massive JSON, that has dynamic fields.

Aka sometimes an extra fields pops into existance.

I would like to map that object to a single java POJO, and if it doesn't find my field, fuck it, I don't care, null. But don't trow an exception.

@JsonIgnoreProperties(ignoreUnknown = true)
public class RepresentationObject {

    @IDK( /* if not found" */ default = "null") 
    @JsonProperty("Components")
    private List<Whatever> nullableWhoCares;
}

Or some such

Top answer
1 of 5
2

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?

2 of 5
2

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);
Find elsewhere
🌐
JBoss.org
developer.jboss.org › message › 358212
Detach entities - Obtaining a clear pojo| JBoss.org Content Archive (Read Only)
This new implementation allows us to recurse any object graph looking for PersistentCollection fields that might be hidden within it, as long as they are accessible via a get* method. package org.hibernate.collection; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Collection; import java.util.Map; import org.apache.commons.beanutils.PropertyUtils; import org.hibernate.LazyInitializationException; /** * Some utils methods to get a complete clean POJO from an entity bean with hibernate specific * fields stripped out.
🌐
Google Groups
groups.google.com › g › jooq-user › c › 8MBETRVrLCM
Insert only some fields from a POJO
Either email addresses are anonymous for this group or you need the view member email addresses permission to view the original message ... I'm using a JOOQ-generated POJO as the receiver of JSON data coming from a REST request. This is a simple CRUD request, specifically Create. For a number of columns I have default values defined in the database schema and, naturally, the primary key is generated at the database end. However, the POJO has all these properties, which end up being null, indistinguishable from "Undefined" in Java.
🌐
Java67
java67.com › 2019 › 09 › 3-ways-to-ignore-null-fields-in-json-java-jackson.html
3 ways to ignore null fields while converting Java object to JSON using Jackson? Example | Java67
And, if that's precisely what you want, then you can ignore the fields with null values using @JsonInclude annotation in Jackson. Btw, if you are new to Jackson library then you can also check out this Jackson Quick Start: JSON Serialization with Java Made Easy course on Udemy.
🌐
Stack Overflow
stackoverflow.com › questions › 52268949 › remove-non-printable-character-from-pojo-in-java-8
string - Remove non printable character from pojo in java 8 - Stack Overflow
I want to remove the non-printable character only for the String fields in the poject, I know we can use public String removeNonPrintable(String field) { return field.replaceAll("[^A-Za-z0-9]"...
Top answer
1 of 1
2
@JsonInclude(JsonInclude.Include.NON_NULL)
public class TransactionHistoryBO { ... }

@JsonInclude(JsonInclude.Include.NON_NULL)
public class TransactionHistoryResponse { ... }

public class App {

    public static void main(String... args) throws JsonProcessingException {

        ObjectMapper om = new ObjectMapper();

        TransactionHistoryResponse thr = new TransactionHistoryResponse();
        TransactionHistoryBO thbo = new TransactionHistoryBO();
        thbo.setProductName("TEST");
        thr.setTransactions(new ArrayList<TransactionHistoryBO>());
        thr.getTransactions().add(thbo);
        System.out.print(om.writerWithDefaultPrettyPrinter().writeValueAsString(thr));
    }

}

Produces output :

{
  "transactions" : [ {
    "productName" : "TEST"
  } ]
}

No other annotation is used. Just add @JsonInclude annotation to classes not properties.


UPDATE:

Add a custom JacksonJsonProvider to your application

@Provider
public class CustomJsonProvider extends ResteasyJackson2Provider {

    @Override
    public void writeTo(Object value, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException {

        ObjectMapper mapper = locateMapper(type, mediaType);
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

        super.writeTo(value, type, genericType, annotations, mediaType, httpHeaders, entityStream);
    }

}

Register this provider in your web.xml

<context-param> 
    <param-name>resteasy.providers</param-name> 
    <param-value>com.package.CustomJsonProvider</param-value> 
</context-param>

Tested with and without this and it works.

🌐
Baeldung
baeldung.com › home › json › jackson › removing json elements with jackson
Removing JSON Elements With Jackson | Baeldung
January 8, 2024 - Explore how to remove JSON elements using Jackson and understand the process through practical examples.
🌐
MarkLogic
docs.marklogic.com › guide › java › binding
POJO Data Binding Interface (Java Application Developer's ...
Skip to main contentSkip to search · Powered by Zoomin Software. For more details please contactZoomin
🌐
MarkLogic
docs.marklogic.com › 9.0 › guide › java › binding
POJO Data Binding Interface (Java Application Developer's Guide) — MarkLogic 9 Product Documentation
Since a PojoRepository is bound to a specific POJO class, calling PojoRepository.deleteAll removes all POJOs of the bound type from the database. You can only use the data binding interfaces with Java POJO classes that can be serialized and deserialized by Jackson.
🌐
Stack Abuse
stackabuse.com › ignore-null-fields-with-jackson-in-java-and-spring-boot
Ignore Null Fields with Jackson in Java and Spring Boot
June 14, 2023 - In this tutorial, learn how to ignore null fields when serializing POJOs with Jackson, in Java and Spring Boot. You can do this by customizing the ObjectMapper instance, changing the default-property-inclusion property in your properties file, customizing the Jackson2ObjectMapperBuilder instance, ...
🌐
TutorialsPoint
tutorialspoint.com › article › how-can-we-ignore-the-fields-during-json-serialization-in-java
How can we ignore the fields during JSON serialization in Java?
September 1, 2025 - If there are fields in Java objects that do not wish to be serialized, we can use the @JsonIgnore annotation in the Jackson library. The @JsonIgnore can be used at the field level, for ignoring fields during the serialization and deserialization.