filter out null values from JSON using gson

I am looking for a way to eliminate attributes with empty collections or null values using gson.

Aiperiodo periodo = periodoService();
//periodo is obtained from a service method with various values
Gson gson = new Gson();
String json = gson.toJson(periodo);

After printing the json, this is the output:

{"idPeriodo":121,"codigo":"2014II",
"activo":false,"tipoPeriodo":1,
"fechaInicioPreMatricula":"may 1, 2014",
"fechaFinPreMatricula":"jul 1, 2014",
"fechaInicioMatricula":"jul 15, 2014",
"fechaFinMatricula":"ago 3, 2014",
"fechaInicioClase":"ago 9, 2014",
"fechaFinClase":"dic 14, 2014",
"fechaActa":"ene 15, 2015",
"fechaUltModificacion":"May 28, 2014 12:28:26 PM",
"usuarioModificacion":1,"aiAvisos":[],
"aiAlumnoCarreraConvalidacionCursos":[],
"aiAlumnoMatriculas":[],"aiMallaCurriculars":[],
"aiAlumnoCarreraEstados":[],"aiAdmisionGrupos":[],
"aiMatriculaCronogramaCabeceras":[],
"aiAlumnoCarreraConvalidacions":[],
"aiHorarioHorases":[],"aiAsistencias":[],
"aiAlumnoPreMatriculas":[],
"aiAlumnoMatriculaCursoNotaDetalles":[],
"aiOfertaAcademicas":[],"aiTarifarios":[]}

For instance, I would like to remove the collection aiAvisos from the json. Is there a way to achieve this? I am dealing with multiple collections, this is just an example, I really need to eliminate them from the json.

I desire the output to be like this:

{"idPeriodo":121,"codigo":"2014II",
"activo":false,"tipoPeriodo":1,
"fechaInicioPreMatricula":"may 1, 2014",
"fechaFinPreMatricula":"jul 1, 2014",
"fechaInicioMatricula":"jul 15, 2014",
"fechaFinMatricula":"ago 3, 2014",
"fechaInicioClase":"ago 9, 2014",
"fechaFinClase":"dic 14, 2014",
"fechaActa":"ene 15, 2015",
"fechaUltModificacion":"May 28, 2014 12:28:26 PM",
"usuarioModificacion":1}

I attempted setting the collections to null, but there doesn't seem to be a method for that in the documentation...

If you have any suggestions, please share. By the way, I have updated the json that was posted a few minutes ago.

Thank you to everyone who took the time to read this!

Answer №1

How to Remove Empty Collections from JSON Using Gson:

  • Start by converting the JSON String into a Map<String,Object> by utilizing the Gson#fromJson() method.
  • Next, iterate through the map and eliminate any entries that are either null or empty ArrayList.
  • After filtering, reconstruct the JSON String from the modified map using the Gson#toJson() function.

Tip: Enhance the readability of the output JSON by setting the configuration to enable pretty printing using GsonBuilder#setPrettyPrinting().

For a code example, refer to Remove empty collections from a JSON with Gson

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

Javascript error specific to Internet Explorer. Can't retrieve the value of the property 'childNodes'

After removing the header information from the XML file, the issue was resolved. Internet Explorer did not handle it well but Firefox and Chrome worked fine. An error occurred when trying to sort nodes in IE: SCRIPT5007: Unable to get value of the proper ...

Adding pictures to Cloudinary

My goal is to upload files directly to Cloudinary using nodejs. I have managed to achieve success when I manually set the path of the image I am uploading, as shown below: cloudinary.uploader.upload('./public/css/img/' + data.image) However, whe ...

Combining two XPaths into a single XPath can be achieved by using various

HTML <li class="wdappchrome-ai" data-automation-id="searchInputAutoCompleteResult" tabindex="-2" aria-posinset="1" aria-setsize="3"> <span data-automation-id="searchInputAutoCompleteResultFullText"> <span style="font-weight:500"> ...

Tips for choosing the right ticket option: e-ticket, mobile ticket, or self-print ticket

Presenting my element: <div id="ctl00_MasterContent_FareOptionsWebPart_FareOptionsFares_ctl123_FarePoint_Outbound28_1" class="FareOptionsFarePoint Outbound Single F28 J1 fakecheck filtered fakechecked" **data-fulfilment="ToD Kiosk SelfPrint MobileTicke ...

Transform a log file into a JSON structure

In my log file titled request.log, the following entries are present: [2022-06-30T09:56:40.146Z] ### POST https://test.csdf/auth/send_otp { "method": "POST", "headers": { "User-Agent": "testing&q ...

Developing a multi-graph by utilizing several JSON array datasets

Currently exploring D3 and experimenting with creating a multi-line graph without utilizing CSV, TSV, or similar data formats. The key focus is on iterating over an array of datasets (which are arrays of objects {data:blah, price:bleh}). I am trying to a ...

Is it possible for me to verify the login status of an Auth0 user within my custom NextJS _app.js file?

Currently working on a NextJS application with nextjs-auth0 for authentication, which is completely new to me. I followed the documentation's suggestion and wrapped my _app.js with UserProvider, also using getInitialProps to set a global online/offlin ...

Utilize jQuery to encode PHP JSON data

After making an ajax call to PHP, I am receiving JSON encoded data: [ { "id":"4", "name":"Kg", "vital_sign_list_id":"3", "created":"2016-03-01 18:52:27", "modiefied":"2016-03-01 18:52:27" }, { "id":"5", ...

Changing the event handler of a jQueryUI accordion dynamically from "click" to "mouseover" as needed

I am facing a scenario where I need to drag an item from a list and drop it into a target within an accordion. The challenge is that the target may be in a panel that is not currently open. To address this issue, I am looking to dynamically switch the acc ...

Combining Mongoose query results in a for loop: A step-by-step guide

i am trying to combine the results of a mongoose query into a single JSON object. however, i am encountering an issue where i am passing an array to mongoose. specifically, the array looks like this: Modem Serial: [11111111111,nodata,3333333333333333] wh ...

Attempting to save an image captured in a Vue form and then transmit it to the Laravel backend

Hey everyone, I'm a newcomer to Vue and Laravel and I'm currently working on a REST project. I have a form that allows users to upload an image, but I keep encountering an error when trying to store it in the database: "Request failed with ...

Implementing concurrent operations in React Native using Firebase, combining async/await with Promise.all

import fire from '../config/fire'; const db = fire.firestore(); class InitialDb extends Component { constructor(props) { super(props); this.state = { schools: '', students: '', }; } async compo ...

Scrolling to zoom in on the div content

I need the ability to resize the content within a div without changing the size of the div itself when the user scrolls. The function I currently have is as follows: var zoomable = document.getElementById('zoomable'), zX = 1; window.addEvent ...

Using React Native to make a POST request to Mockable.io's API using Axios

Currently, I am working on a react native app where users can place orders for items. At the moment, I am able to retrieve the following data from my Mockable API: Items Pictures Icons However, I am facing an issue with posting to another Mockable API ...

PHP is unable to decode JSON that has been encoded using json_encode

In order to save a large geojson file (around 60mb) to a database, I am using the following code to encode it: // controller public function importZones () { ini_set('max_execution_time', '0'); ini_set('memory_limit' ...

Sending data through URL links in HTML

$.post("/diabetes/ropimages/getcount.php",{patientId:$("#patient_id").val()} ,function(data1){ //alert(data1); var count = data1; var patientId = $("#patient_id").val(); var reportId; for( var i = 1 ; i <= count ; i++) { var imageLink =&a ...

Threejs file exporter from Blender generating corrupted files

My Blender model seems to be causing issues: After using the threejs exporter in Blender 2.7, the exported json file contains numerous null or 0 values: { "metadata": { "formatVersion" : 3.1, "generatedBy" : "Blender 2.7 Exporter", ...

RestKit: Convert Local to-many relationship into a JSON array containing object ids

Encountering a challenge with RestKit mapping: Within my local Core Data setup, I am working with objects Group and Message where a Group can have multiple Messages and a Message can be sent to multiple Groups. My goal is to map the relationships of Messa ...

Modify the design of the button in the CSS code

I am facing an issue with the layout of the Visible Columns button and unable to standardize it like the buttons above using CSS enter image description here The code snippet for the Visible Columns button is as follows: import React, { useState, useEffe ...

Tips for sending custom props to a dynamic page in Next.js

I have created a component called Card.js which is responsible for linking to dynamic pages when a card is clicked. My goal is to pass a value, such as 'category', to the dynamic page [id].js so that I can implement additional logic there. Card. ...