簡體   English   中英

將 POJO 的 null 字段保留為 map java 中的鍵

[英]Keep null fields of a POJO as keys in map java

我有一個 POJO,並使用 object 映射器將其轉換為 map。 我希望 map 在其條目集中包含 POJO 的所有字段,即使它們的值為 null。 因此,該條目可能是我正在創建的 map 中的 null。

Map<String, Object> oldDetails = objectMapper.convertValue(oldFields, Map.class);

我試過使用下面的代碼片段,但這對我沒有幫助。

objectMapper.setDefaultPropertyInclusion(JsonInclude.Value.construct(JsonInclude.Include.ALWAYS, JsonInclude.Include.ALWAYS));

我可以在這里使用任何其他想法嗎?

我的 POJO:

@JsonInclude(NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class BaseFields {

    @JsonProperty("number") protected String number;
    @JsonProperty("name") protected String name;
    @JsonProperty("dob") protected String dob;

}

還有其他類從 BaseFields 繼承,例如。

@JsonInclude(NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
public class CustomerBaseFields extends BaseFields {
    @JsonProperty("email") protected String email;         
}

現在有一種方法可以將 ChangedBaseFields 的實例轉換為 map。

ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, true);
        objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
        objectMapper.setDefaultPropertyInclusion(JsonInclude.Value.construct(JsonInclude.Include.ALWAYS, JsonInclude.Include.ALWAYS));
        Map<String, Object> oldDetails = objectMapper.convertValue(baseFields, Map.class);

But say if a field like email is null in object, I'm not getting a key email in my map.

這是一個簡單的代碼,證明您的代碼實際上可以在沒有任何其他配置的情況下使用默認 ObjectMapper。

package java17test;

import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.Map;

public class Test {
    public static void main(String[] args) {
        var objectMapper = new ObjectMapper();
        
        var oldFields = new TestClass();
        oldFields.setFirstName("first name");

        Map<?, ?> oldDetails = objectMapper.convertValue(oldFields, Map.class);
        oldDetails.forEach((key, value) -> System.out.println(key + "=" + value));
    }

    static class TestClass {
        private String firstName;
        private String lastName;

        public String getFirstName() {
            return firstName;
        }

        public void setFirstName(String firstName) {
            this.firstName = firstName;
        }

        public String getLastName() {
            return lastName;
        }

        public void setLastName(String lastName) {
            this.lastName = lastName;
        }
    }
}

Output:

firstName=first name
lastName=null

您可能有一個XY 問題,因為您在對 vbezhenar 的回答的評論中提到您的意圖是比較相同類型的兩個對象的字段,以找出哪些字段已更改。

您不必使用 Jackson 來執行此操作。

這是比較兩個對象的簡單純 Java(無依賴關系)方式:

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;

public class Utils {
    /**
     * Compares two objects of the same type, returning the field values that are different.
     *
     * @param o1 an object
     * @param o2 another object
     * @return a map of field name to a two-element array of the two different values of o1 and o2
     */
    public static <T> Map<String, Object[]> comparePojos(T o1, T o2) throws IllegalAccessException {
        Map<String, Object[]> diffs = new LinkedHashMap<>();

        for (Field field : o1.getClass().getDeclaredFields()) {
            field.setAccessible(true);
            Object[] values = {field.get(o1), field.get(o2)};
            if (!values[0].equals(values[1]))
                diffs.put(field.getName(), values);
        }
        return diffs;
    }
}

class UtilsDemo {
    public static void main(String[] args) throws IllegalAccessException {
        SamplePojo a = new SamplePojo("alice", 42);
        SamplePojo b = new SamplePojo("bob", 42);
        Utils.comparePojos(a, b).forEach((k, v) -> System.out.println(k + ": " + Arrays.toString(v)));
    }
}

class SamplePojo {
    public SamplePojo(String name, int age) {
        this.name = name;
        this.age = age;
    }

    private String name;
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM