gson returns null if not deserialized

Issue with Gson deserialization when not handling specific fields

public class Mode {
    @Expose(deserialize = false)
    public final List<String> list;

    public Mode(List<String> list) {
        this.list = list;
    }

    public List<String> getList() {
        return list;
    }
}

List objects only serialize and do not deserialize in this scenario

public class Entity {
    public Mode setting = new Mode(Arrays.asList("1", "2"));
}

Solution involves adding a deserialization exclusion strategy:

Gson gson = new GsonBuilder().setPrettyPrinting().addDeserializationExclusionStrategy(new ExclusionStrategy() {
            @Override
            public boolean shouldSkipField(FieldAttributes f) {
                Expose annotation = f.getAnnotation(Expose.class);

                if (annotation == null) {
                    return false;
                }
                return !annotation.deserialize();
            }

            @Override
            public boolean shouldSkipClass(Class<?> clazz) {
                return false;
            }
        }).create();
        var s = """
                {
                  "setting": {
                    "list": [
                      "1",
                      "2",
                      "3"
                    ]
                  }
                }
                                
                """;
        System.out.println(gson.fromJson(s, Entity.class).setting.getList());

Error occurs where the list field of the Mode class returns as null during deserialization of the Entity class

Answer №1

Awesome solution

//First, retrieve the JSON object
JsonObject jsonObject = gson().fromJson("", JsonObject.class);
//Next, iterate through all fields of the entity
for (Field configField : klass.getDeclaredFields()) {
    configField.setAccessible(true);
    if (!jsonObject.has(configField.getName())) {
        continue;
    }
    //Then, deserialize the field
    Object setting = gson().fromJson(jsonObject.get(configField.getName()).toString(), configField.getType());
    //Further, get all fields of the setting
    for (Field settingField : setting.getClass().getDeclaredFields()) {
        settingField.setAccessible(true);
        if (settingField.isAnnotationPresent(Expose.class)) {
            if (!settingField.getAnnotation(Expose.class).deserialize()) {
                Field declaredField = ReflectUtil.getField(setting.getClass(), settingField.getName());
                //Now, use the value from the entity to set the value of the setting
                declaredField.set(setting, ReflectUtil.getFieldValue(ReflectUtil.getFieldValue(entity, configField.getName()), settingField.getName()));
            }
        }
    }
    //Finally, set the value of the entity using the value from previous steps
    configField.set(entity, setting);
}

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

The foundation of the Selenium framework seems to be malfunctioning

As a beginner in Selenium, I attempted to create a basic framework that isn't functioning correctly. I utilized TESTNG and DataProvider annotation. If anyone could provide assistance or recommend an alternative framework/code, it would be greatly app ...

Using Node.js to read and replicate a JSON file

As someone who is relatively new to the world of NODE.JS, I am eager to level up my skills. Currently, I have a NODE.JS script that gathers data from a feed, resulting in a large JSON file. This file is then used by webpages and mobile apps to display con ...

Sending the "accurate" data from the specific cell in a UITableViewController to a ViewController

I'm encountering the same issue here. I am struggling to pass the precise data from one TableViewController to another ViewController. Even though I have all the necessary data from JSON, when I select a row, it displays the data from the last row ins ...

Set an array to a JSON object as a fresh entity

My challenge involves working with an array that contains certain values. let myArray = [value1, value2]; I am looking to generate a JSON object in the format shown below: { "field": "[value1, value2]" } ...

Trigger a PHP script to execute whenever a user updates a row in a MySQL/WordPress database

I am currently in the process of developing a small web application that will retrieve data from a specific row in a database on a WordPress based website. This data will be used to populate an announcers section for a radio station on another website. Th ...

How can I obtain tabular output for Boto3 | Python data?

When using the AWS CLI, you have the option to set the output format as either json or table. While I am able to obtain JSON output using json.dumps, is there a way to achieve output in table format? I attempted to use pretty table but did not succeed. ...

An unexpected special character (ï) was discovered at the beginning of the JSON parsing process in Java while utilizing the sample-json-1.1.1

I am encountering an issue while parsing a Har file generated from the ie11 browser using sample-json in Java. The error message I am receiving is "Unexpected character (ï) at position 0". Interestingly, the same code works perfectly fine with a Har file ...

Utilizing Selenium with Java: Extracting Data from a Single Dropdown Menu (Time Selection)

Hey there: I am facing an issue with extracting data from a calendar field. I am trying to extract the information (HH.MM.AM/PM) from a single date field, but so far, it has been unsuccessful. This is the code snippet I have been using: WebElement currT ...

In search of an efficient method to verify JSON input using the Play framework

While I find it easy to read and validate the expected fields in a JSON input, I struggle with properly handling an exception if an unexpected field is found. It would be helpful if the play framework could provide some guidance on this issue. I could manu ...

There are no attributes currently present in the Document Object Model for the Tooltip

Can anyone assist me with an issue I'm having regarding tooltips? Some tooltips are missing certain attributes like title, and I need help identifying the tooltip shown in the image below. Just to note, there is no attribute related to the tooltip pr ...

Sorting through JSON information based on specific attributes and criteria

Consider this JSON object: { 'name' : 'John', 'friends' : [ { 'id' : 1, 'name' : 'George', 'level' : 10 }, { 'id' : 2, 'name ...

after ajax post, enhance original object by merging with the latest server values

After making a call to the server and successfully saving some data, I need to update the JSON array object that I have with new values. Here is a snippet of my code: [ { "id": 1, "uuid": "ce54acea-db20-4716-bceb-2f3deb1b2b86", "name": null, ...

Exploring the capabilities of IBM Integration Bus in handling JSON parsing operations

Hello, I am currently facing an issue with parsing JSON data in the IIB Toolkit. The error message thrown by the java compute node is: "java.lang.NoClassDefFoundError: org.json.JSONObject" When attempting to parse incoming JSON messages using UTF-8 encodi ...

The JSON object is not defined

I have a question regarding an AJAX page request using a PHP file to handle queries in my MySQL database. The PHP file seems to be working properly, but I am encountering some issues. Here is the code snippet: function updateForm(){ ID = $(&ap ...

Dealing with Expressjs error messages: When sending data that is strictly a string,

It has been quite challenging to find information on this topic, as most inquiries involve incorrectly serialized objects. I am attempting to send a string, not an object. Here is the request right before it is sent off. The payload can be properly handle ...

Guide to accessing HTML elements and saving them in a JSON formatted text using JavaScript

If you have an html form with labels, select boxes, and radio buttons, you can use javascript to store the child elements of that form in a json string format. Here is an example: { "label": { "content": "This is a label" }, "textbox" ...

Find the most affordable rate in the JSON data without knowledge of the parent label

I am seeking to extract the best deal from JSON data obtained through an API call and decoded using json_decode. The structure is as follows: products productnumber -> price $product_array['products'][..changingnumber..]['value'] ...

Create a dynamic process that automatically generates a variety of div elements by using attributes from JSON data

Is there a way to organize the fixtures from this data into separate divs based on the matchday attribute? I've tried using Underscore's groupBy function but I'm unsure how to dynamically distribute the data into individual divs for each re ...

Converting strings into the right values through parsing

I have a JSON response that contains multiple suggestions, but I only want to parse and extract the 4 "collation" results: jQuery191029421305245357143_1380819227858( { "responseHeader": { "status": 0, "QTime": 127 }, "command": ...

Remove a JSON object that corresponds to a particular value

I am in need of modifying a JSON file in a specific way. My goal is to remove an entire object from the file based on a certain condition. In this case, the condition is that "name": "value1_1:value1_2" The value of value1_1 is what I am targeting for ...