Is it possible to create an instance of a superclass and automatically instantiate a specific subclass based on the parameters provided?

Currently, I am utilizing Google's GSON package which can be found at this link

My task involves converting JSON data to Java objects.

Below is a snippet of the code where the conversion process takes place:

Gson gson = new Gson();
Type collectionType = new TypeToken<Collection<QueryProperty>>() {}.getType();
Collection<QueryProperty> queryProperties = gson.fromJson(query, collectionType);

The QueryProperty class includes these fields along with their respective getters and setters:

int id;
String uri;
String name;
Set<QueryValue> values;
String selected;

Prior to this, the QueryValue class had the following fields (with getters/setters):

int id;
String uri;
String name;

Now, I have a requirement to introduce different types of QueryValue instances.

Firstly, I aim to implement a NumericQueryValue class (as a subclass of QueryValue) to enable setting lower and upper bounds for database queries.

double lower;
double upper;

In addition, it is necessary to create a ResourceQueryValue class (also a subclass of QueryValue) that mirrors the original QueryValue structure:

int id;
String uri;
String name;

Is there a method to achieve this? I intend to keep the QueryValue class generic while dynamically determining the correct subclass based on the provided JSON parameters.

If my explanation is unclear, please feel free to ask for clarification.

Answer №1

Currently, Gson lacks an easy way to handle polymorphic deserialization, aside from creating custom deserialization code. However, there are indications that the upcoming release will address this issue with a built-in solution.

Here are some previous discussions and examples related to this topic on StackOverflow.com:

  • Dealing with deserializing a generic type with unknown compile-time information using field indicators
  • How to parse JSON data with no fixed structure in a specific field using GSON
  • Serialization and deserialization of JSON objects using Google's Gson library
  • Implementing polymorphism with Gson

Answer №2

It appears that a solution to your problem might involve developing a specialized deserializer for verifying values, or an instance creator if you simply need to generate an instance based on the type.

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

Tips for ensuring confidential communication between clients and servers

My project utilizes AngularJS on the client-side and Express JS on the server-side for data communication using the http post method. Currently, when a http request is sent, the server responds with JSON data that gets displayed in the client browser. I wa ...

Is there a way to utilize code to invoke a method of an object? For example, calling MyObject.XVariable(//some function

I have a unique object that gets its data filled from an API call. let MyDog = { Name: 'Dog', } let arrayFunctions; fetchDogsFunctions(dogAPIUrl).then(res => { // The results variable contains an array of functions the dog can do, such as get ...

The error message "The 'int' object does not have a 'replace' attribute when loading initial data in Django" was encountered

Looking to understand how to load initial data into a model using loaddata. Here is an example of my JSON structure: [ { "model": "locations.location", "pk": 1, "fields": { "name": "Cafe" } } ] This is what my model.py looks l ...

Altering the value of a form upon submission

Struggling with Javascript to update an input value before submitting and storing it in a MySQL table, I encounter the issue of getting a blank row in the database. The code snippet causing this problem looks like this: document.getElementsByName('w ...

Adjust the navigation menu to display or hide as the page is being scrolled

Implementing an offset to display/hide the navigation menu when the page is scrolled 100px. Attempted to modify from lastScroll = 0 to lastScroll = 100 but it did not work as expected. Jquery: Fiddle // Script lastScroll = 0; $(window).on('scroll&ap ...

"Experiencing a problem with Next.js 13 where the User Context is not functioning properly outside of _app

When using Next.js 13 and the user context, I've noticed that it doesn't function properly outside of _app.tsx. Any idea why? src>context>UserPositionContext.tsx import { createContext, useContext, useState } from "react"; const ...

Best practices for alerting using React and Redux

As I delve into Redux for the first time and work on revamping a fairly intricate ReactJS application using Redux, I've decided to create a "feature" for handling notifications. This feature will involve managing a slice of state with various properti ...

The sample Ajax XML code provided by W3Schools is ineffective

While studying xml parsing in ajax on w3schools.com, I came across an example that functioned perfectly online. However, when I saved it to my desktop as abc.html and note.xml, the XML values weren't displaying. Even though the HTML elements were vis ...

Converting JSON-style data into a string with the power of node mysql

Just a quick note - I'm a total newbie in the world of web development, so I might be missing an obvious solution here. My challenge is to insert a dataset into a MySQL database using nodejs/expressjs/mysql. I've managed to establish a connecti ...

Using Jquery to dynamically add or remove a class based on scrolling behavior

Can someone help me with identifying the position of an element so that when the user scrolls to it and it appears on the screen, an icon can be highlighted? Currently, the script I am using adds the class too early, closer to the bottom of the block. I w ...

Mastering the art of switching between different application statuses in ReactJS

As a newcomer to reactJS, I am exploring ways to make one of my components cycle through various CRUD states (creating object, listing objects, updating objects, deleting objects). Each state will correspond to displaying the appropriate form... I have co ...

Unspecified origins of Js in Chrome Extension

console.log(chrome.runtime.sendMessage({from:"script2",message:"hello!"})); However, attempting to send the message from a background script to a content script is proving to be unsuccessful. https://i.stack.imgur.com/ERgJB.png ...

What is the best way to execute a JSONP request using JQuery while incorporating Basic Authentication?

What is the best way to utilize JQuery in calling a JSONP API that needs basic authentication? Is there a way to automate this process, or does it require user intervention to input their credentials into the login prompt? ...

Modifying one input can impact other input elements without any form of direct connection between them

Below is the HTML code snippet: <tr *ngFor="let row of formData; let i = index" [attr.data-index]="i"> <td *ngFor="let rowdata of formData[i]; let j = index" [attr.data-index]="j"> <input type="checkbox" name="row-{{i}}-{{j}}" [ ...

Alternative to using the disabled attribute in JavaScript to make a checkbox read-only option

Does anyone know how to make a checkbox readonly so that its value can be submitted, while also disabling it? Using the disable attribute prevents the value from being submitted, and setting it as readonly doesn't seem to work for checkboxes. Your as ...

"The debate over using 'stringly typed' functions, having numerous redundant functions, or utilizing TypeScript's string enums continues to divide the programming

I have a specific object structure that contains information about countries and their respective cities: const geo = { europe: { germany: ['berlin', 'hamburg', 'cologne'], france: ['toulouse', ' ...

Activate DivMenu's second list item automatically

I've been trying to use the trigger function multiple times, but it just won't work. I need help with auto-triggering the menu of the second list element. Can someone please assist me? Here is a snippet of my code: $("document").ready(functio ...

Error encountered: API key is required - Issue found in: /node_modules/cloudinary/lib/utils.js at line 982

I encountered an issue with cloudinary while trying to upload photos on my website after adding a new function for Facebook login. "/home/ubuntu/workspace/YelpCamp/node_modules/cloudinary/lib/utils.js:982 throw "Must supply api_key"; ^ Mus ...

Showing content within a <div> element using Jquery when clicked

Currently, I am using JSON to retrieve data : $(document).ready(function () { var url = '<%: Url.Content("~/") %>' + "Products/GetMenuList"; $.getJSON(url, function (data) { $.each(data, function (index, dataOption) { ...

What is the process for linking read-only methods to Redux object instances?

Let's say I have a "user" object stored in redux, with fields for first name and last name (interface User { firstName : string, lastName : string} if using typescript). After retrieving a user from redux, I want to obtain the full name of the user by ...