Faster XML ‐ Object mapper [Jackson – Marshal and Unmarshal Java Objects to JSON] - Yash-777/MyWorld GitHub Wiki

Faster XML - Object mapper

FasterXmlObjectMappperJSON objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

FasterXmlObjectMappperJSON.java Example to read and write from file
public class FasterXmlObjectMappperJSON {
    
    static String payLoadJsonFile = "D:/emp.json";
    public static void main(String[] args) throws StreamReadException, DatabindException, IOException {
        Employee e = Employee.builder()
                .id(777).age(30)
                .name("Yashwanth").first("Yash").last("M")
                //.address("HYD")
                .build();
        
        FasterXmlObjectMappperJSON obj = new FasterXmlObjectMappperJSON();
        obj.writeObj(e);
        
        Employee readJson = obj.readJson();
        System.out.println("readJson:"+readJson);
    }
    public File getFile(String payLoadJsonFile) {
        return new File(payLoadJsonFile);
        //new java.io.File(getClass().getClassLoader().getResource( payLoadJsonFile ).getFile());
    }
    public ObjectMapper getObjectMapper() {
        ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper();
        objectMapper.configure(com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.configure(com.fasterxml.jackson.databind.SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true);
        objectMapper.setSerializationInclusion(com.fasterxml.jackson.annotation.JsonInclude.Include.NON_NULL);
        //objectMapper.writer(new DefaultPrettyPrinter());
        return objectMapper;
    }
    public Boolean writeObj(Employee result) throws StreamWriteException, DatabindException, IOException {
        File file = getFile(payLoadJsonFile);
        ObjectMapper objectMapper = getObjectMapper();
        objectMapper.writerWithDefaultPrettyPrinter().writeValue(file, result);
        try {
            String nodeName = "name";// Employee.name
            JsonNode readTree = objectMapper.readTree(file);
            if (readTree.get(nodeName) != null) { 
                System.out.println("Specific Node:"+readTree.get(nodeName).toString());
            }
            System.out.println("Full Tree:\n"+readTree.toPrettyString());
            return Boolean.TRUE;
        } catch (JsonProcessingException e) {
            return Boolean.FALSE;
        }
    }
    public Employee readJson() throws StreamReadException, DatabindException, IOException {
        File file = getFile(payLoadJsonFile);
        ObjectMapper mapper = getObjectMapper();
        return mapper.readValue(file, new com.fasterxml.jackson.core.type.TypeReference<Employee>(){});
    }
}
@Data @Builder @AllArgsConstructor @NoArgsConstructor
//@lombok.NoArgsConstructor(lombok.AccessLevel.PRIVATE)
class Employee {
    int id, age;
    String name, first, last, address;
}

Enum JsonInclude.Include used to Exclude property in JSON-Response

Enumeration used with JsonInclude to define which properties of Java Beans are to be included in serialization.

Constant Summary
ALWAYS       Value that indicates that property is to be always included, independent of value of the property.
NON_DEFAULT  Value that indicates that only properties that have values that differ from default settings (meaning values they have when Bean is constructed with its no-arguments constructor) are to be included.
NON_EMPTY    Value that indicates that only properties that have values that values that are null or what is considered empty are not to be included.
NON_NULL     Value that indicates that only properties with non-null values are to be included.

Global feature that can be used to suppress all failures caused by unknown (unmapped) properties:

// jackson 1.9 and before
objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// or jackson 2.0
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
Click to see more:
`@EnableWebMvc @Configuration` class WebConfig
@Bean
public ObjectMapper objectMapper() {
    final ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true);
    return objectMapper;
}

@EnableWebMvc @Configuration
@PropertySource(ignoreResourceNotFound = true, value = {"file:${CONFIG_HOME}/application.properties", "file:${CONFIG_HOME}/application_override.properties"})
public class WebConfig extends WebMvcConfigurerAdapter {
    private static final Logger LOGGER = LoggerFactory.getLogger(WebConfig.class);
    @Bean
    public static PropertySourcesPlaceholderConfigurer propertyPlaceHolderConfigurer() {
        return new PropertySourcesPlaceholderConfigurer();
    }

    @Override
    public void addCorsMappings(final CorsRegistry registry) {
        super.addCorsMappings(registry); // https://en.wikipedia.org/wiki/Cross-origin_resource_sharing

        registry.addMapping("/*/**").allowedMethods("PUT", "DELETE", "POST", "GET", "OPTIONS").allowedOrigins("*");
        registry.addMapping("/*").allowedMethods("PUT", "DELETE", "POST", "GET", "OPTIONS").allowedOrigins("*");
    }
    
    @Bean
    public ObjectMapper objectMapper() {
        final ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true);
        return objectMapper;
    }
    @Bean
    public MappingJackson2HttpMessageConverter jaksonMessageConverter() {
        final MappingJackson2HttpMessageConverter jaksonMessageConverter = new MappingJackson2HttpMessageConverter();
        jaksonMessageConverter.setObjectMapper(objectMapper());
        return jaksonMessageConverter;
    }
    
    @Bean
    public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> embeddedServletContainerCustomizer() {

        return new WebServerFactoryCustomizer<ConfigurableServletWebServerFactory>() {
            private static final String CONTEXT_PATH = "/api";

            @Override
            public void customize(final ConfigurableServletWebServerFactory factory) {
                int port = 8084;
                try {
                    final String portString = System.getProperty("server.port");
                    if (portString != null) {
                        port = Integer.parseInt(portString);
                    }
                    LOGGER.info("Server running on the port {} ", port);
                } catch (final NumberFormatException e) {
                    LOGGER.debug("Error while reading server.port ", e);
                }
                LOGGER.trace("Customizing embeddedServlet container  using port :{} and contextPath :{}", port, CONTEXT_PATH);
                factory.setPort(port);
            }
        };
    }
}
Jackson JSON - @JsonInclude NON_DEFAULT

To Exclude the Primitive-Property(byte,int,Long,...) in org.springframework.http.ResponseEntity<? extends Object>

@com.fasterxml.jackson.annotation.JsonInclude(com.fasterxml.jackson.annotation.JsonInclude.Include.NON_DEFAULT)
private long version;

// OR

ObjectMapper.setDefaultPropertyInclusion(JsonInclude.Include.NON_DEFAULT);
⚠️ **GitHub.com Fallback** ⚠️