简体   繁体   中英

Convert Java POJO to Map without JSON serialization

I'd like to convert a Java POJO into a Map without using JSON serialization for the properties (eg that Date's are converted to a long or a ISO8601 String). I just want the fields to be retained as they are.

For example if I have a POJO defined like this:

public class MyPojo {
    private Date date;
    private String x;

    public MyPojo(Date date, String x) {
        this.date = date;
        this.x = x;
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    public String getX() {
        return x;
    }

    public void setX(String x) {
        this.x = x;
    }
}

I know I can use Jackson as described in this Stackoverflow question but the result is not what I want. For example if I do:

Map<String, Object> x = new ObjectMapper().convertValue(new MyPojo(new Date(), "x"), new TypeReference<Map<String, Object>>() {});
System.out.println(x);

I get this result:

{date=1528521584984, x=x}

whereas I would simply like a Map retaining the java.util.Date instance without being serialized.

Note that I obviously would like this work for nested Pojo's such as:

public class MyPojo {
   private MyOtherPojo otherPojo;
   ...
}

How can I achieve this?

Jackson will serialize the Date to a timestamp format by default (number of milliseconds since January 1st, 1970, UTC). @JsonFormat annotation can be used to control the date format on individual classes.

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss")
private Date date;

First off, going from a POJO to a Map seems like a bad idea. But I guess that you have reasons for wanting to do it ...

The simple approach is to just create a HashMap and populate it using a sequence of put calls. That gives you a map that contains the same information as the original POJO, but is not "connected" to is.

If you want the Map to be a view of the original POJO, there are 3rd-party libraries that can be used to do this. For example, org.apache.commons.beanutils has classes for wrapping an POJO that follows the JavaBeans conventions as a DynaBean . You can then adapt that as a Map using DynaBeanMapDecorator .

Mapping nested POJOs to nested maps would require more work. (And it contradicts your requirement that you can get the value of getData() as a Date POJO rather than as a Map !)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM