Gson: Omitting a field in a specific class without the use of annotations - Part 2

Currently I am working on serializing a Java object to JSON using Gson. My goal is to exclude a specific field in one class while keeping it in another.

Here's a snippet of the code:

Class A {
 var a;
 var b;
}

Class B {
 var a;
 var c;
}

Class C {
 class A;
 class B;
}

I need to skip a only in A, without affecting B. However, I cannot use annotations on the fields and manually removing a from object A is not an option. I am seeking a generic approach to achieve this.

A similar question was asked on Stack Overflow: Gson: How to exclude specific fields from Serialization without annotations. The solution proposed by Nishant aligns with my thinking, but there was an error in the condition provided.

f.getDeclaringClass() == c

The GetDeclaringClass method returns the type of the class, not the parent class.

I have implemented custom exclusion strategies using Gson where I can utilize methods like shouldSkipClass(class) and shouldSkipField(fieldAttributes). However, I am looking for a way to combine these strategies to skip a field only if it belongs to a specific class.

shouldSkipFieldUnderClass(class, fieldAttributes)

Are there any other approaches to achieve this? Have I overlooked something in my implementation? Any suggestions on how to skip fields in a specific class using Gson would be appreciated.

Answer №1

I need to make sure that the field a is excluded from Class A, but not from Class B.

To achieve this, simply mark the field a as transient

Class A {
 var transient a;
 var b;
}

Class B {
 var a;
 var c;
}

Class C {
 class A;
 class B;
}

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

Ways to prevent users from pushing multiple child data or adding more than one child to a specific child in the Firebase database

How can we limit users from pushing more than one piece of data to the Firebase database in terms of security rules? I have attempted this approach without success. { "rules": { ".read": false, ".write": false, "voters": { // En ...

setting up my personal Chrome browser add-on

After creating a Chrome Extension, I successfully installed it but then uninstalled it. Now that I want to re-install it, the directions indicate that I should drag and drop the extension onto the Chrome Extensions page. When attempting to do so, I mista ...

Python script to extract data from a JSON file

Struggling to read data from a JSON file and display the values? Having trouble figuring out how to access all the values from the first dictionary in the list? Here's what you want to print: website: https://www.amazon.com/Apple-iPhone-GSM-Unlocke ...

Converting data to a JSON string using jQuery's AJAX method

When I use document.write() for JSON data, it works fine outside of the AJAX call, but not inside the .done() function. I even tried removing the dataType: 'json' parameter, but it still didn't work. $.ajax({ url: "http://api.wundergrou ...

"Unlocking the Power of Pandas Dataframes: A Guide to Parsing MongoDB

I have a piece of code that exports JSON data from a MongoDB query like this: querywith open(r'/Month/Applications_test.json', 'w') as f: for x in dic: json.dump(x, f, default=json_util.default) The output JSON looks like this: ...

Exploring the parsing of nested JSON in Android using Kotlin

As I am relatively new to Kotlin programming, I'm facing difficulties in parsing JSON data. My goal is to extract "title" and "body" from the "notification" within the "unackd" array only. This is my current implementation: private fun parse(): Bool ...

Tips for eliminating the page margin in Java when converting HTML using iTextPdf with HTMLConverter

No matter how hard I've tried, setting the body with padding: 0 and margin: 0, as well as attempting to set the doc() with setMargin, nothing seems to be effective ...

Accessing Key / Value pairs of a JSON object using Newtonsoft Library

I've come across several questions and answers related to my current task, but despite reading through the responses, I'm still struggling to extract the key and value from this JSON. Here's the JSON data that is being returned: { "@odata. ...

Unlock the full potential of Scala JSON by merging properties together

I'm currently working with a case class that looks like this: case class User(name: String). My goal is to create a JSON Reads converter for it, so I can use the following code snippet: val user = userJson.validate[User] However, the incoming JSON ...

Utilize JSON RPC v2 via HTTP protocol

Are there any Go projects that have successfully implemented JSON RPC 2.0 over HTTP, specifically with support for batched queries? I'm aware of a built-in solution in Go, but it doesn't work over HTTP. I also looked at Gorilla's v2 folder ...

Is there a way to send JSON using ExpressJS in UTF-8 encoding?

Currently facing an issue with my new web app that I haven't encountered in the past. Experimenting with a simple code snippet like this: var jsonToSend = {hello: "woørld"}; app.get('/someUrl', function(req, res) { res.setHeader('Co ...

Converting a JSON string into a dynamic object through serialization

Apologies if my terminology is incorrect, but I am trying to achieve the following: Retrieve a JSON string from a URL Parse this string into an object Usually this would be simple for me as the JSON objects I work with have static names. However, the ch ...

What methods are most efficient for retrieving JSON data in regards to performance?

I've been utilizing HttpWebRequest to fetch json information from a third-party site, but the performance has been lacking. Would switching to wcf provide significant improvements? Your expertise and insights on this matter would be greatly appreciat ...

The API response contains a date format that is not recognized

When the API Server sends a response with the token expiration date, it is in this specific format: 2022-05-09T02:11:27.747 Can you identify the format of this date? ...

Analyzing a JSON Structure Containing Numerous Sub-Objects

<script type="text/javascript" src="http://static.stackmob.com/js/2.5.3-crypto-sha1-hmac.js"></script> <script type="text/javascript"> $j.ajax({ dataType : 'json', url : "/api/core/v2/groups/", //or any other res ...

Occasional TypeError when receiving JSONP response using jQuery .ajax()

Occasionally, I encounter an error message stating Uncaught TypeError: undefined is not a function when processing the JSONP response from my jQuery .ajax() call. The JSON is returned successfully, but sometimes this error occurs during the reading process ...

Implementing a switch to trigger a JavaScript function that relies on a JSON object retrieved from a GET request

Having some trouble using a toggle to convert my incoming Kelvin temperature to Celsius and then to Fahrenheit. It loads properly as default Celsius when the page first loads, but once I try toggling the function outside of locationLook, it doesn't se ...

Parsing JSON using dotted paths in Python

Are there any Python libraries available on PyPI that allow me to parse JSON using dot-separated paths and order-independent arrays? 1. dot separated path 2. order independant in case of array Data : "attr1": [ { "attr2": "val2" }, ...

Error 406 occurred when attempting to consume a REST service in org.springframework.web

I am encountering a 406 response error with "HttpMediaTypeNotAcceptableException" when trying to call a REST service from AngularJS. AngularJS REST Call $http.get('/MongoMicroServices-0.1.0/user/getByMailId/' + $scope.username).then(function(re ...

Guide for Uploading, presenting, and storing images in a database column with the help of jQuery scripting language

What is the best method for uploading, displaying, and saving an image in a database using jQuery JavaScript with API calls? I am working with four fields in my database: 1. File ID 2. Filename 3. Filesize 4. Filepath ...