Dealing with null object values during Jackson parsing

I am currently utilizing the Jackson library and attempting to accomplish a task as described here

BaseOperationRequest.java

@JsonTypeInfo(
   use = JsonTypeInfo.Id.NAME,
   include = JsonTypeInfo.As.PROPERTY,
   property = "command"
)
@JsonSubTypes({
   @JsonSubTypes.Type(name = "ZADD", value = ZAddBaseOperationRequest.class)
})
public class BaseOperationRequest {
   public short operationId;
   public Command command;
   public String gameId;
   public String key;
}

ZAddBaseOperationRequest.java

public class ZAddBaseOperationRequest extends BaseOperationRequest{
   public Map<String, Double> members;
}

Command.java

public enum Command{
  ZADD,
  HSET
}

The issue arises when I attempt to pass an object from a REST call which resembles this structure:

@RestController
public class MyController{
   // Currently set as GET, will be changed to POST with RequestBody in the future 
   @RequestMapping(value = "/process/{object}", method = RequestMethod.GET, produces = "application/json")
    public @ResponseBody ResponseEntity process(@Pathvariable String object){
        System.out.println(object);// The output here seems correct--->(A)
        BaseOperationRequest[] baseOperationRequestArray = new ObjectMapper().readValue(object, BaseOperationRequest[].class);// Exception occurs here --->(B)
        System.out.println(baseOperationRequestArray);
    }
}

Now, when making the call like so:

1st scenario CALLING WITHOUT MEMBERS MAP:

<server>:<port>/.../process/[{"operationId":1,"command":"ZADD","gameId":"t5","key":"abc"}]

The process method is being invoked and although Jackson is instructed to create an instance of ZAddBaseOperationRequest when encountering ZADD as a command, the command itself appears assigned as null in the resulting object.

Please elaborate on why this might be happening? Where did the value of command disappear to?

2nd scenario CALLING WITH MEMBERS MAP: :/.../process/[{"members":{"a":1.0},"operationId":1,"command":"ZADD","gameId":"t5","key":"abc"}]

In this case, the result at (A) shows [{"members":{"a":1.0,b, indicating that some part of the GET request is missing.

This situation is quite frustrating :). Thanks for your assistance in advance.

Your help would be greatly appreciated!

Answer №1

Avoid sending JSON as a path parameter; it's not considered best practice.

To resolve this issue, include visible=true in the JsonTypeInfo annotation. Your updated declaration should look like this:

@JsonTypeInfo(
  use = JsonTypeInfo.Id.NAME,
  include = JsonTypeInfo.As.PROPERTY,
  property = "command",
  visible = true
)

According to the Jackson documentation for visible:

The property determines whether the type identifier value will be included in the JSON stream passed to the deserializer (true) or handled and removed by TypeDeserializer (false). By default, it is set to false, meaning that Jackson handles and removes the type identifier from the JSON content before passing it to the JsonDeserializer.

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

What method would you recommend for modifying HTML text that has already been loaded using JSP?

Is there a way to update text on an HTML document without reloading the entire page? I'm looking to create a simple "cart" functionality with 5 links on a page. When a link is clicked, I want it to increment the "items in cart" counter displayed on th ...

Retrieving JSON data from outside the React root directory

My current project includes an older javascript/php application with numerous JSON files used to retrieve data from the database. As I plan to migrate some modules to React, I am wondering if it's possible to still fetch data from these JSON files wi ...

Is there a way to remove data from both a JSON file and an HTML document?

Currently, I am facing a challenge with my code. I am unsure how to implement the functionality to delete a row when clicking on the X button and retrieve the unique ID of that particular row to append it to the URL. Unfortunately, finding the correct meth ...

Does the sequence matter when studying JavaScript, Ajax, jQuery, and JSON?

Expanding my job opportunities is a top priority for me, which is why I am dedicated to learning JavaScript, AJAX, jQuery, and JSON. As I delve into these languages, I can see how they all have roots in JavaScript. My main inquiry is about the relationsh ...

Combining Power BI with Spring Angular for Seamless Integration

I am in the process of building a web platform with Spring and Angular. One important element I want to include is Power Bi integration, allowing me to generate datasets and reports using Spring and display charts in Angular. Are there any resources or t ...

Tips for inserting information into data tables

Let me begin by outlining the process I am undertaking. I interact with a remote JSON API to retrieve data, perform some basic operations on it, and ultimately produce a data row consisting of three variables: Date, name, and message (think of an IRC chat ...

Save the JSON response array into the session

After a successful login attempt, my LoginActivity sends the username and password to a URL and receives a success status in return. I am looking to store the JSON response containing user ID, name, and email information in a session so that I can retrieve ...

Strip the Python dictionary from the JSON file output

After researching various resources, such as a post on Stack Overflow titled Remove python dict item from nested json file, I am still struggling to make my code work. My JSON data is quite complex, with nested dictionaries and lists scattered throughout. ...

Error in parsing JSON with Google Gson

Can anyone help me with putting a Map into listMap using Gson and displaying it in listView? I am having trouble understanding how to do it. Below is my code snippet for the button onClick event: map = new HashMap<>(); map.put("title", edttext1.get ...

Unable to process: ' (dynamic) =>Meta' as it is not compatible with type '(String, dynamic) => MapEntry<dynamic, dynamic>' for 'transform'

Examining my json data: { "data": { "id": 1, "title": "Test-1", "description": "Description of test-1.", "category_id": "1", "product_sizes": [ ...

Transmit JSON information from one webpage and dynamically retrieve it from another page via AJAX while both pages are active

I am attempting to transfer JSON data from page1 when the submit button is clicked and then retrieve this data dynamically from page2 using AJAX in order to display it in the console. I am unsure of the correct syntax to accomplish this task. There was a s ...

The output I receive when making a jQuery POST request is a response generated by my index controller, although I am not specifically directing it there as I have

Currently, I am working with the latest version of codeigniter. After sending a post request, all I am receiving back is my view. This situation has left me puzzled. Listed below are my routes: $route['default_controller'] = "veebn"; $route[&a ...

Tips on how to incorporate information into variables in cucumber's feature files?

Currently tackling a UI selenium project where the goal is to extract String data from the UI and convert it into a variable within my .feature scenario file. In order to illustrate, let's take an example where I only have access to the customerID: ...

Exploring the depths of nested documents in Mongoose and MongoDB

I am dealing with a schema that is recursively nested, similar to how comments function on a blog. I am trying to figure out the best approach to extract an individually nested document that could be buried within multiple layers of nesting. I know that I ...

c# JavaScriptConverter - understanding the deserialization of custom properties

I'm facing an issue where I have a JSON serialized class that I am trying to deserialize into an object. For example: public class ContentItemViewModel { public string CssClass { get; set; } public MyCustomClass PropertyB { get; set; } } Th ...

Can you tell me the JSONPATH symbol that signifies a mismatch with a regular expression?

My Zabbix item has the PreProcessing JSONPath as shown below: Item key: vfs.fs.get Preprocessing JSONPath script: $.[?(@.fstype =~ '{$FSTYPE.MATCHES}')] The resulting structured JSON list looks like this: [{ "fsname": "/" ...

The error message encountered in Python is: "Cannot iterate over the '_csv.writer' object due to a TypeError."

I'm currently facing an error while parsing json to csv: for i in data: TypeError: '_csv.writer' object is not iterable Here is the code snippet: import json import csv with open("Data.json", 'r') as file: data = json.load( ...

Developing a unique style.css for WordPress using package.json and Gulp

My experience with Gulp is fairly new, but I've been using it to streamline my build process for developing WordPress themes. I have successfully configured my package.json file and now I want my style.css file to dynamically reflect the version speci ...

What is the proper way to change this JavaScript variable into JSON format?

I have a JavaScript variable containing data that I need to convert into valid JSON format for easier parsing. The current variable structure is as follows: { "machines": [{ "category": "Category 1", "items": [{ "name": "Te ...

The RemoteWebDriver is currently unable to upload the file

Having trouble uploading a file on a demo site using RemoteWebDriver? You’ve successfully done it with the regular WebDriver driver, but now facing issues with RemoteWebDriver. The exception thrown is :"org.openqa.selenium.WebDriverException: Settin ...