Search code examples
javajsonpojo

java set object field equal another field upon instantation


I am mapping a json list to java list of objects. The class I am mapping to has an extra time field (local time).

In the incoming json, the timestamp field appears as 1510549200000 (UTC time stamp) for example. This example corresponds to a date: Monday, November 13, 2017 12:00:00 AM GMT-05:00 in local time

upon mapping to the class, I need to assign a local time based on the incoming UTC value.

The mapping is done as follows:

List<myClass> items = objectMapper.readValue(
       jsn_a.toString(), new TypeReference<List<myClass>>() {});

and in the Class constructor I have is:

public myClass() {
    this.localTime= myUTCTime; 
}

But when I look at the resulting list of objects, I see that localTime is still set to null.

I can see why this is happening (constructor is called first); but how do I go about assigning the utc timestamp to the localTime field during the object creation.


Solution

  • Generally, Java-JSON mapping libraries invoke the no arg constructor to unserialize a JSON object into a Java Object.
    According to the libraries you use you could use a way to set the fields from the arg constructor.
    Or more simply invoke the setter on the field after default unserialization :

    Foo foo = ... // unserialize from json
    foo.setLocalTime(myUTCTime);