Omitting certain values in jackson

I am currently working with Object Mapper and I am seeking a way to exclude certain fields based on specific values.

Imagine having an object structured like this:

public static class Data 
{
    int id;
    int value;
}

Let's assume that the value is typically 60. In order to reduce the length of serialized data, I would like to only serialize ids when the value equals 60. Is there a method to accomplish this?

(By the way, I attempted to utilize the 'ignore null' functionality by returning null for that particular value, but unfortunately it hindered the reusability of the beans)

Answer №1

If you want to create a custom serializer for this particular class, here is an example of how you can achieve that:

@JsonSerialize(using = CustomDataSerializer.class)
class Data {

    public static final int DEFAULT_VALUE = 60;

    private int id;
    private int value = DEFAULT_VALUE;

    // include getters, setters, toString method, etc.
}

The implementation of the custom serializer would look like this:

class CustomDataSerializer extends JsonSerializer<Data> {

    @Override
    public void serialize(Data value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
        jgen.writeStartObject();
        jgen.writeFieldName("id");
        jgen.writeNumber(value.getId());
        if (value.getValue() != Data.DEFAULT_VALUE) {
            jgen.writeFieldName("value");
            jgen.writeNumber(value.getValue());
        }
        jgen.writeEndObject();
    }
}

Here is an example of how you can use the custom serializer:

// import statements

public class CustomSerializerExample {

    public static void main(String[] args) throws IOException {
        List<Data> dataList = new ArrayList<Data>(10);
        for (int index = 0; index < 10; index++) {
            Data data = new Data();
            data.setId(index);
            data.setValue(index < 6 ? Data.DEFAULT_VALUE : index);
            dataList.add(data);
        }
        System.out.println(dataList);

        ObjectMapper mapper = new ObjectMapper();
        String jsonOutput = mapper.writeValueAsString(dataList);

        System.out.println(jsonOutput);

        CollectionType collectionType = mapper.getTypeFactory().constructCollectionType(ArrayList.class, Data.class);
        List<Data> deserializedList = mapper.readValue(jsonOutput, collectionType);

        System.out.println(deserializedList);
    }

}

When running the above code snippet, the output will be:

[Data [id=0, value=60], Data [id=1, value=60], Data [id=2, value=60], Data [id=3, value=60], Data [id=4, value=60], Data [id=5, value=60], Data [id=6, value=6], Data [id=7, value=7], Data [id=8, value=8], Data [id=9, value=9]]
[{"id":0},{"id":1},{"id":2},{"id":3},{"id":4},{"id":5},{"id":6,"value":6},{"id":7,"value":7},{"id":8,"value":8},{"id":9,"value":9}]
[Data [id=0, value=60], Data [id=1, value=60], Data [id=2, value=60], Data [id=3, value=60], Data [id=4, value=60], Data [id=5, value=60], Data [id=6, value=6], Data [id=7, value=7], Data [id=8, value=8], Data [id=9, value=9]]

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ensure the JSON file aligns with the TypeScript Interface

I am working with a config.json file. { "profiler": { "port": 8001, "profilerCache": { "allowedOriginsRegex": ["^http:\/\/localhost:8080$", "i"] } }, "database": { "uri": "mongodb+srv://...", "dbName": "profiler", ...

Using ngFor in Angular to display the API response

I am having trouble displaying a JSON response in my web panel. When attempting to show the full response, everything works perfectly. However, when I try to use ngFor, I encounter the following errors in the browser: ERROR TypeError: Cannot read property ...

Struggling to extract specific information from a json array using Angular, my current approach is only retrieving a portion of the required data

My JSON structure is as shown in the image below: https://i.stack.imgur.com/5M6aC.png This is my current approach: createUIListElements(){ xml2js.parseString(this.xml, (err, result) => { console.log(result); this.uiListElement = result[ ...

Retrieve the non-empty attributes of a JSON object

I have a function in Typescript that extracts specific values from a JSON data object, some of which may be empty. How can I retrieve only certain data fields? Here is the function: let datosCod; for (let get in Object.keys(transfConsData)) { co ...

Developing J2EE servlets with Angular for HTTP POST requests

I've exhausted my search on Google and tried numerous PHP workarounds to no avail. My issue lies in attempting to send POST parameters to a j2ee servlet, as the parameters are not being received at the servlet. Strangely though, I can successfully rec ...

What is the method for including as: :json in your code?

I have a file with the extension .ts, which is part of a Ruby on Rails application. The code in this file looks something like this: export const create = async (params: CreateRequest): Promise<XYZ> => { const response = await request<XYZ> ...

Exploring JSON data in real-time

My goal here is to utilize the variables retrieved from the route to determine which blog to access from the JSON file. The JSON file consists of an array of sections, each containing an array of blogs. Although the code works flawlessly when I manually s ...

Set an array to a JSON object as a fresh entity

My challenge involves working with an array that contains certain values. let myArray = [value1, value2]; I am looking to generate a JSON object in the format shown below: { "field": "[value1, value2]" } ...

Retrieving information from a .json file using TypeScript

I am facing an issue with my Angular application. I have successfully loaded a .json file into the application, but getting stuck on accessing the data within the file. I previously asked about this problem but realized that I need help in specifically und ...

Unable to retrieve the key value from a child object in Angular 2 when working with JSON Data

Currently, I am using Angular and attempting to extract data from the child object's key value. Here is the JSON data provided: "other_lessons": [ { "id": 290, "name": "Christmas Test #290", "course": { "id": ...

Exploring TypeScript Object Properties in Angular 2

How can I extract and display the ID and title of the Hero object below? The structure of the Hero interface is based on a Firebase JSON response. hero.component.ts import {Component, Input} from 'angular2/core'; import {Hero} from '../mod ...

Exploring Angular 5's *ngFor directive with an array of objects

Here is the data I am working with: Initial set of data: var input = [ {ru: "R201", area: "211", unit: "211"}, {ru: "R201", area: "212", unit: "NONE"}, {ru: "R201", area: "HCC", unit: "NONE"}]; Desired result data: var result = [ {area: ...

How to conceal duplicate items in Angular2

In my Angular 2/4 application, I am fetching data from a web API (JSON) and displaying it in a table. In AngularJS, I use the following code: <tbody ng-repeat="data in ProductData | filter:search | isAreaGroup:selectedArea"> <tr style="backgro ...

Parse the local JSON file and convert it into an array that conforms to an

My goal is to extract data from a local JSON file and store it in an array of InputData type objects. The JSON contains multiple entries, each following the structure of InputData. I attempted to achieve this with the code snippet below. The issue arises ...

Retrieve the radio button value without using a key when submitting a form in JSON

Looking to extract the value upon form submission in Angular, here is the code: In my Typescript: constructor(public navCtrl: NavController, public navParams: NavParams, public modalCtrl: ModalController, public formBuilder: FormBuilder, public alertCtrl ...

Exploring the Nested JSON Data Loop with *ngFor in Angular 5/4

Recently I started working with Angular, and I've created a service to iterate over nested JSON data for my list. export const CATEGORIES: Category[] = [ { id: 1, categoryName:'Accessories', subcatName: [ {subcategory: & ...

Tips and tricks for displaying JSON data in Angular 2.4.10

In my Angular project, I am facing an issue while trying to display specific JSON data instead of the entire JSON object. Scenario 1 : import { Component, OnInit } from '@angular/core'; import { HttpService } from 'app/http.service'; ...

Ensuring a Generic Type in Typescript is a Subset of JSON: Best Practices

I am interested in achieving the following: interface IJSON { [key: string]: string | number | boolean | IJSON | string[] | number[] | boolean[] | IJSON[]; } function iAcceptOnlyJSON<T subsetof IJSON>(json: T): T { return json; ...

What is the best method for inserting a hyperlink into the JSON string obtained from a subreddit?

const allowedPosts = body.data.children.filter((post: { data: { over_18: any; }; }) => !post.data.over_18); if (!allowedPosts.length) return message.channel.send('It seems we are out of fresh memes!, Try again later.'); const randomInd ...

Struggling to convert a JSON response into an object model using TypeScript in Angular?

I'm encountering a problem when trying to convert a JSON response into an object. All the properties of my object are being treated as strings, is that normal? Below is my AJAX request: public fetchSingle = (keys: any[]): Observable<Medal> =&g ...