Generate instances of the identical class with distinct attributes

Is it possible in Java to create objects of the same class with different variables each time?

For instance:
I have a method that retrieves data from a URL containing a JSON file, and I want to use this data to create a post object.

ObjectMapper mapper = new ObjectMapper();

public Post getData(String ... url) throws StreamReadException, DatabindException, MalformedURLException, IOException {
    return mapper.readValue(new URL(url[0]), Post.class);
}

However, the .JSON data could be structured like:

{ "name": "Bob" }

Or it could be something more complex like:

{ "color": "Red", "width": "200", "height": "150" }

or any other format.

Answer №1

When Post is a subclass of either Map or JsonNode, it has the capability to store any key-value pairs.

However, if Post is defined with only one field like below, then it is limited to that structure:

public class Post {
  String title;
}

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

A guide on accessing JSON data by index in PHP

Here are three straightforward lines of code: $input = @file_get_contents("php://input"); $event_json = json_decode($input,true); print_r($event_json); The first two lines are used to convert JSON data into an array in PHP, and the third line displays a ...

The Jetty server is unable to provide JSON responses

Whenever I use the command mvn jetty:run to initiate my server, it fails to return JSON formatted strings. Instead, it only returns raw strings or "null" for all objects. In the code snippet for my endpoint, you can observe that there is no variation in r ...

Automatically rotate Xcode simulator to landscape orientation on iPhone/iPad using Selenium

After examining the Appium log, it appears that it is indicating landscape mode with the desired capabilities being set as follows: [debug] [XCUITest] Setting initial orientation to 'LANDSCAPE' To achieve this, I am currently using the followin ...

Guide to include particular data from 2 JSON objects into a freshly created JSON object

I have extracted the frequency of countries appearing in an object (displayed at the bottom). The challenge I am facing is that I require geocode information to associate with country names and their frequencies, so that I can accurately plot the results o ...

How can I ensure that chromedriver in my Test Automation Suite directory is always kept up to date automatically?

Currently, my Automation framework utilizes Selenium and Python to operate. The Chrome browser is run using the chrome driver stored within a specific directory in the automation framework. However, the issue arises when the chrome driver undergoes updates ...

Is there a way to combine two JSON objects within an Android spinner?

After fetching data from my database, is it feasible to combine both objects into a single object? Below is the Android code snippet for retrieving data for a spinner: spinner1 = (Spinner) findViewById(R.id.sp1); final List<String> list1 = ...

Struggling with parsing a JSON array of objects?

{ "-6M7BoTyaAplYy120JAi": { "Address": "sample", "ID": "sample", "Name": "sample", "PhoneNumber": "sample" }, "-6M7Bp ...

Eliminate the use of backslashes in JSON responses when using the WordPress REST API

As I work on extending the Wordpress Rest API, I encounter backslashes even after adding json flags to eliminate them. Below is what I am attempting: stripslashes(json_encode(['success'=> true], JSON_FORCE_OBJECT | JSON_HEX_APOS)); The outpu ...

Creating a JSON object nested by primary key using Django queryset

I'm trying to convert a queryset into a unique JSON object representation. In this representation, each primary key of the model will be a key in the JSON object, and its corresponding value would be another JSON object containing all other fields. m ...

Best way to create a 3D array in PHP

I am trying to structure an array in PHP that resembles the following format: _________________________________________ |time | event | childEvents | |_____|_______|__________________________| |9:00 |Event1 | String[]{subE11, subE12} | |_____ ...

What is the method for retrieving data while utilizing NSURLSession?

As a newcomer to iOS development, I am navigating the world of Swift with minimal experience in Objective-C. While exploring ways to retrieve data from a JSON file on the Web using NSURLSession, I encountered some challenges understanding certain concepts. ...

Managing duplicate xpaths in Selenium with Java

Seeking assistance with dynamically selecting items from a drop-down menu based on input. The challenge arises when values share the same name. For example, consider this Cucumber statement: When I go to the "Inventory" / "Inventory" application When ut ...

The JSON outcome lacks a constructor that supports 0 arguments

While trying to create my JSON action, I ran into an issue. The problem lies in the fact that when I try to return a JsonResult, it is being flagged with an error message stating 'JSON result does not contain a constructor that takes 0 arguments&apos ...

php$json_data = json_decode($response);

I am brand new to PHP coming from a background in Python. I was fairly comfortable with retrieving JSON results from websites in Python, but for some reason, I can't seem to get it working in PHP. Here is the code snippet I'm using: <?php $ ...

Some elements are not visible when inspecting the source code

Hidden fields are essential in my jsp form. Interestingly, when I check the page source in a browser, only the first hidden field is displayed, not the second one. <input type="hidden" name="url" id="url" value="<%=url%>" /> <input type="hi ...

Utilizing Cookies in an AJAX Request for Cross-Domain Communication with Pure Javascript

I am in the process of developing an Analytics application and I'm seeking a method to uniquely identify each user's device. Currently, my approach involves generating a "cookie" from the server side to track all page clicks and interactions thro ...

Can you explain the concept of being "well-typed" in TypeScript?

The website linked below discusses the compatibility of TypeScript 2.9 with well-defined JSON. What exactly does "well-typed" JSON mean? As far as I understand, JSON supports 6 valid data types: string, number, object, array, boolean, and null. Therefore, ...

Transmitting JSON data object

Sending a JSON Object to JSP Page After following the provided link, I discovered that one of the answers suggests creating a JSON object using the following constructor: JSONObject jsonObj=new JSONObject(String_to_Be_Parsed); Upon downloading the JSON ...

Locating and selecting a boolean checkbox with Selenium and Java: A step-by-step guide

I'm currently attempting to click a primefaces select boolean checkbox using the ID, but I'm encountering an issue. The exception message states: org.openqa.selenium.NoSuchElementException: Cannot locate an element using By.id: runDARtest1 I&ap ...

Retrieve the first two elements from an array and iterate through each of them using a foreach

Currently, I have JSON data formatted like this: https://i.stack.imgur.com/PqOQ0.png I am attempting to create URLs using a foreach loop for an API that requires start and finish dates as parameters. For example, here is a sample URL -> My question is, ...