JodaTime LocalTime to JSON - Actual Stack Overflow - java

I am trying to serialize Java objects to JSON. One of my Java objects has a JodaTime LocalTime object as one of its fields.
A fair number of my Java objects also have various fields that are Collections that could be empty. I want to prevent the serialization of JSON that looks like this:
{id: 2348904, listOfThings: [], listOfStuff: [], nowASet: []}
In this scenario where those three Collections are empty, I would rather see this JSON:
{id: 2348904}
The correct way to do such a thing is to configure the ObjectMapper with the following line of code:
objectMapper.setSerializationInclusion(Include.NON_EMPTY);
This works just fine...until I hit that Java object with the LocalTime inside of it. That's when I get an actual java.lang.StackOverflowError.
It seems to be ping-ponging between JodaDateSerializerBase.isEmpty() and JsonSerializer.isEmpty(). I'm not sure how, though, because they don't call each other.
I managed to make a SSSSSSCCCCEEEE, or whatever the hell the acronym is, as follows:
package whatever.you.like;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.joda.JodaModule;
import org.joda.time.LocalTime;
import org.junit.Test;
public class TestClass {
public class JodaMapper extends ObjectMapper {
private static final long serialVersionUID = 34785437895L;
public JodaMapper() {
registerModule(new JodaModule());
}
public boolean getWriteDatesAsTimestamps() {
return getSerializationConfig().isEnabled(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
}
public void setWriteDatesAsTimestamps(boolean state) {
configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, state);
}
}
private class Thing {
private LocalTime localTime;
public Thing() {}
public void setLocalTime(LocalTime localTime) {
this.localTime = localTime;
}
public LocalTime getLocalTime() {
return localTime;
}
}
#Test
public void extendObjectMapperTest() throws JsonProcessingException {
JodaMapper objectMapper = new JodaMapper();
objectMapper.setWriteDatesAsTimestamps(false);
objectMapper.setSerializationInclusion(Include.NON_EMPTY);
Thing thing = new Thing();
LocalTime localTime = new LocalTime(12389340L);
thing.setLocalTime(localTime);
System.out.println("Never manages to print this out: " + objectMapper.writeValueAsString(thing));
}
#Test
public void configureObjectMapperTest() throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new JodaModule());
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
objectMapper.setSerializationInclusion(Include.NON_EMPTY);
Thing thing = new Thing();
LocalTime localTime = new LocalTime(12389340L);
thing.setLocalTime(localTime);
System.out.println("Never manages to print this out: " + objectMapper.writeValueAsString(thing));
}
}
I tried both extending the ObjectMapper and configuring the ObjectMapper, and I get the same error each time.
Dependencies:
JodaTime 2.6
FasterXML's Jackson 2.5.0
FasterXML's Jackson-DataType-Joda 2.5.0
Interestingly, you can find in that GitHub a unit test ("testLocalDateSer()") that claims to succeed using the Include.NON_EMPTY qualifier. I fail to see how it could possibly function.

Upgrade to
FasterXML's Jackson 2.5.3
FasterXML's Jackson-DataType-Joda 2.5.3.
This works.
#Test
public void configureObjectMapperTest() throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new JodaModule());
// objectMapper.configure(SerializationFeature.WRITE_DURATIONS_AS_TIMESTAMPS, false);
objectMapper.setSerializationInclusion(Include.NON_EMPTY);
Thing thing = new Thing();
LocalTime localTime = new LocalTime(12389340L);
thing.setLocalTime(localTime);
System.out.println("Never manages to print this out: " + objectMapper.writeValueAsString(thing));
}

Related

Use Jackson ObjectMapper to convert between java.time.Instant and java.util.Date

I'm trying to use Jackson's ObjectMapper to map between two classes (SrcMessage and DestMessage, for example).
My SrcMessage class looks something like:
class SrcMessage {
public Instant workTime;
}
My DestMessage class looks like:
class DestMessage {
public Date workTime;
}
I'm using the ObjectMapper like so:
SrcMessage src = new SrcMessage ();
src.workTime = Instant.now ();
ObjectMapper mapper = new ObjectMapper ( );
mapper.registerModule (new JavaTimeModule ());
DestMessage dest = mapper.convertValue (src, DestMessage.class);
When I make the convertValue call I get an exception with a message:
com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.util.Date` out of VALUE_NUMBER_FLOAT token
at [Source: UNKNOWN; line: -1, column: -1] (through reference chain: DestMessage["workTime"])
at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:59)
at com.fasterxml.jackson.databind.DeserializationContext.reportInputMismatch(DeserializationContext.java:1468)
at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1242)
at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1148)
at com.fasterxml.jackson.databind.deser.std.StdDeserializer._parseDate(StdDeserializer.java:517)
at com.fasterxml.jackson.databind.deser.std.DateDeserializers$DateBasedDeserializer._parseDate(DateDeserializers.java:200)
at com.fasterxml.jackson.databind.deser.std.DateDeserializers$DateDeserializer.deserialize(DateDeserializers.java:290)
at com.fasterxml.jackson.databind.deser.std.DateDeserializers$DateDeserializer.deserialize(DateDeserializers.java:273)
at com.fasterxml.jackson.databind.deser.impl.FieldProperty.deserializeAndSet(FieldProperty.java:138)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:293)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:156)
at com.fasterxml.jackson.databind.ObjectMapper._convert(ObjectMapper.java:4231)
I'm stuck. I thought that the JavaTimeModule would be enough to handle this conversion, but apprently not. Is there some other module that I need? Other suggestions on how to make this work? So far the only solution I've found is to ignore the workTime field when doing the mapping, and then convert the value after the mapper has completed. Needless to say, this works for a simple case, but I'd rather not have to enumerate all of the Instant/Date fields and handle them manually. I'd much rather have Jackson handle it internally.
Any ideas?
For converting dates I would recommend using benefits of types, instead of using Jackson ObjectMapper. Use Date from(Instant instant) static method to convert java.time.Instant type into java.util.Date type.
You can do it as presented in example:
import java.time.Instant;
import java.util.Date;
public class StackOverflowAnswer {
public static void main(String[] args) {
SrcMessage srcMessage = new SrcMessage(Instant.now());
DestMessage destMessage = DestMessage.fromSrcMessage(srcMessage);
}
}
class SrcMessage {
public Instant workTime;
public SrcMessage(Instant workTime) {
this.workTime = workTime;
}
}
class DestMessage {
public Date workTime;
DestMessage(Date workTime) {
this.workTime = workTime;
}
static DestMessage fromSrcMessage(SrcMessage srcMessage) {
return new DestMessage(Date.from(srcMessage.workTime));
}
}

How do I update RestTemplate to correctly map Java Dates?

I have an issue where my RestTemplate.postForEntity(url, restRequest, RepoResponse.class) call is failing because it can't deserialise dates of the form:
2019-02-01T12:00:00.000-0500
because of the missing colon in the timezone.
Based on this answer, it looks like I want to change the date formatting of my RestTemplate's ObjectMapper.
I've tried a solution here:
https://stackoverflow.com/a/38286322/14250
Which gives me the following code:
restTemplate = new RestTemplate();
ObjectMapper objectMapper = new ObjectMapper();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS[XXX][X]");
objectMapper.setDateFormat(format);
MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
messageConverter.setPrettyPrint(false);
messageConverter.setObjectMapper(objectMapper);
restTemplate.getMessageConverters().removeIf(m->m.getClass().getName().equals(MappingJackson2HttpMessageConverter.class.getName()));
restTemplate.getMessageConverters().add(messageConverter);
Unfortunately I get the following error
com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `java.time.OffsetDateTime` (no Creators, like default construct, exist): no String-argument constructor/factory method to deserialize from String value ('2019-02-13T12:33:19.179-0500')
Is there an easy way to make RestTemplate support the above datetime format?
When you are working with java.time.* classes and Jackson is good to start from registering JavaTimeModule which comes from jackson-datatype-jsr310 module.
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import java.time.OffsetDateTime;
public class JsonApp {
public static void main(String[] args) throws Exception {
JavaTimeModule javaTimeModule = new JavaTimeModule();
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(javaTimeModule);
String json = "{\"now\":\"2019-02-01T12:01:01.001-0500\"}";
System.out.println(mapper.readValue(json, Time.class));
}
}
class Time {
#JsonFormat(pattern = "uuuu-MM-dd'T'HH:mm:ss.SSSX")
private OffsetDateTime now = OffsetDateTime.now();
public OffsetDateTime getNow() {
return now;
}
public void setNow(OffsetDateTime now) {
this.now = now;
}
#Override
public String toString() {
return "PrintObject{" +
"now=" + now +
'}';
}
}
Above code prints:
PrintObject{now=2019-02-01T17:01:01.001Z}

SerializationFeature.WRAP_ROOT_VALUE as annotation in jackson json

Is there a way to have the configuration of SerializationFeature.WRAP_ROOT_VALUE as an annotation on the root element instead using ObjectMapper?
For example I have:
#JsonRootName(value = "user")
public class UserWithRoot {
public int id;
public String name;
}
Using ObjectMapper:
#Test
public void whenSerializingUsingJsonRootName_thenCorrect()
throws JsonProcessingException {
UserWithRoot user = new User(1, "John");
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
String result = mapper.writeValueAsString(user);
assertThat(result, containsString("John"));
assertThat(result, containsString("user"));
}
Result:
{
"user":{
"id":1,
"name":"John"
}
}
Is there a way to have this SerializationFeature as an annotation and not as an configuration on the objectMapper?
Using dependency:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.7.2</version>
</dependency>
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Test2 {
public static void main(String[] args) throws JsonProcessingException {
UserWithRoot user = new UserWithRoot(1, "John");
ObjectMapper objectMapper = new ObjectMapper();
String userJson = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(user);
System.out.println(userJson);
}
#JsonTypeName(value = "user")
#JsonTypeInfo(include = JsonTypeInfo.As.WRAPPER_OBJECT, use = JsonTypeInfo.Id.NAME)
private static class UserWithRoot {
public int id;
public String name;
}
}
#JsonTypeName and #JsonTypeInfo together make it possible.
Result:
{
"user" : {
"id" : 1,
"name" : "John"
}
}
I think this has been requested as:
https://github.com/FasterXML/jackson-databind/issues/1022
so if anyone wants a challenge & a chance to make many users happy (it is something that'd be nice to have for sure), it's up for grabs :)
Aside from that one small thing worth noting is that you can use ObjectWriter to enable/disable SerializationFeatures.
String json = objectMapper.writer()
.with(SerializationFeature.WRAP_ROOT_VALUE)
.writeValueAsString(value);
in case you need to sometimes use this, other times not (ObjectMapper settings should not be changed after initial construction and configuration).
You can use the it in the below way, so this property will be applied to throughout the objectMapper usage.
static {
objectMapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
}

How to pass JSON representations of Java Calendar objects to REST service?

Here is a simplified version of my problem. Consider the following REST services...
#Stateless
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_JSON)
#Path("/test")
public class TestResource {
#POST
public Response test(Calendar c) {
System.out.println(c);
return Response.ok(Response.Status.OK).build();
}
#GET
#Path("/getCalendar")
public Response getCalendar() {
return Response.ok(toJSONString(Calendar.getInstance())).build();
}
public String toJSONString(Object object) {
GsonBuilder builder = new GsonBuilder();
builder.setDateFormat("yyy-MM-dd'T'HH:mm:ss.SSS'Z'");
Gson gson = builder.create();
return gson.toJson(object);
}
}
and of course, this...
#ApplicationPath("/rest")
public class RestActivator extends Application {
}
I am using Postman, and at first I get a JSON representation of the Calendar object by sending a GET request to 'http://localhost:8080/ProjectName/rest/test/getCalendar'. I then copy the JSON that gets returned which is
{
"year": 2015,
"month": 5,
"dayOfMonth": 29,
"hourOfDay": 10,
"minute": 7,
"second": 24
}
Then using Postman I send a POST to 'http://localhost:8080/ProjectName/rest/' with the data that was returned to me above. Then the 'javax.ws.rs.NotSupportedException: Cannot consume content type' gets thrown.
How can I fix this so the service can handle Calendar objects (and classes that have Calendar objects as fields)?
Edit:
Yes I am setting the correct content type which is application/json.
Here is the response I am getting...
com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.Calendar out of START_OBJECT token
at [Source: io.undertow.servlet.spec.ServletInputStreamImpl#4cf87599; line: 1, column: 1]
Update:
To get this to work I used #peeskillets solution.
Jackson generally only works with JavaBean style POJOs, which Calendar is not. For these cases, Jackson allows us to create custom Deserializers. Once we create the deserializer, we can register it with the ObjectMapper in a ContextResolver. For example
public class CalendarDeserializer extends JsonDeserializer<Calendar> {
#Override
public Calendar deserialize(JsonParser jp, DeserializationContext dc)
throws IOException, JsonProcessingException {
JsonNode node = jp.getCodec().readTree(jp);
int year = getInt("year", node);
int month = getInt("month", node);
int dayOfMonth = getInt("dayOfMonth", node);
int hourOfDay = getInt("hourOfDay", node);
int minute = getInt("minute", node);
int second = getInt("second", node);
Calendar c = Calendar.getInstance();
c.set(year, month, dayOfMonth, hourOfDay, minute, second);
return c;
}
private int getInt(String name, JsonNode node) {
return (Integer) ((IntNode) node.get(name)).numberValue();
}
}
To register it with the ObjectMapper we can do
ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addDeserializer(Calendar.class, new CalendarDeserializer());
mapper.registerModule(module);
To use the ObjectMapper with our JAX-RS application, we can create it in the ContextResolver, as seen here. You will need to add the jackson-databind as a dependency, if you don't already have it.
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson2.version}</version>
</dependency>
Note that the above dependency already comes with Jackson JSON providers for JAX-RS, so if you already have Jackson JSON support dependency, you won't need it.
I've tested this with the JSON you have provided, and it works fine.
See more about custom deserializers here
You need to pass in proper content type in request and check whether you are giving right path..
So after doing some research and thanks to those who answered ( specifically #peeskillet ) I have come up with 2 solutions to this problem.
Solution 1
Go with #peeskillet 's answer and create a custom deserializer. That worked, and here are the 2 classes I added to get that to work...
import java.util.Calendar;
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.module.SimpleModule;
#Provider
public class ObjectMapperContextResolver implements ContextResolver<ObjectMapper> {
private final ObjectMapper mapper;
public ObjectMapperContextResolver() {
mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addDeserializer(Calendar.class, new CalendarDeserializer());
mapper.registerModule(module);
mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
}
#Override
public ObjectMapper getContext(Class<?> type) {
return mapper;
}
}
as well as the custom Deserializer
import java.io.IOException;
import java.util.Calendar;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.IntNode;
public class CalendarDeserializer extends JsonDeserializer<Calendar> {
private int getInt(String name, JsonNode node) {
return (Integer) ((IntNode) node.get(name)).numberValue();
}
#Override
public Calendar deserialize(JsonParser jp, com.fasterxml.jackson.databind.DeserializationContext dc) throws IOException,
JsonProcessingException {
JsonNode node = jp.getCodec().readTree(jp);
int year = getInt("year", node);
int month = getInt("month", node);
int dayOfMonth = getInt("dayOfMonth", node);
int hourOfDay = getInt("hourOfDay", node);
int minute = getInt("minute", node);
int second = getInt("second", node);
Calendar c = Calendar.getInstance();
c.set(year, month, dayOfMonth, hourOfDay, minute, second);
return c;
}
}
Solution 2
However, I also figured out another solution that may be easier. If I omitted the GSON toJSONString (not sure why I was mixing Jackson and GSON...) in the #GET method and simply returned Response.ok(Calendar.getInstance()).build();, Jackson converted the Calendar object to it's primitive long value. When I passed in a long value to the #POST method with a Calendar object as the method parameter, Jackson was able to deserialize it properly as a Calendar object.
Conclusion
If you want to pass JSON representations of Calendar objects to a REST endpoint, pass it as the long representation.
On the other hand you can always create a custom deserializer if you have a JavaScript Date object or a custom Date object.
I know this is old question, but I just added another constructor with long instead of Calendar so it could deserialize
#POST
public Response test(long c) {
System.out.println(c);
return Response.ok(Response.Status.OK).build();
}
For Example:
public class demo{
String id;
Calendar date;
String tag;
public demo(Calendar date, String tag) {
this.date = date;
this.tag = tag;
}
public demo(long date, String tag) {
this.date = longToCalendar(date);
this.tag = tag;
}
public Calendar longToCalendar(Long epoch) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(epoch);
return calendar;
}
}
#POST
public Response test(Demo demo) {
System.out.println(demo);
return Response.ok(Response.Status.OK).build();
}

Jackson serialization exception when trying to serialize LocalDateTime

I can't figure why when trying to serialize an object I get an exception which looks related to deserialization. My object has a field which is of joda type LocalDateTime
ObjectMapper mapper = new ObjectMapper();
mapper.writeValueAsString(response));
I got the following exception:
org.codehaus.jackson.map.JsonMappingException: java.lang.String cannot be cast to org.joda.time.LocalDateTime
I am trying to serialize. Why it is trying to convert String value to object? I tried to add custom deserializers, but it does not work.
update More of the exception:
org.codehaus.jackson.map.JsonMappingException: java.lang.String cannot be cast to org.joda.time.LocalDateTime (through reference chain: com.my.AccountDetailResponse["registrationDate"])
at org.codehaus.jackson.map.JsonMappingException.wrapWithPath(JsonMappingException.java:218) ~[jackson-mapper-asl-1.9.13.jar:1.9.13]
at org.codehaus.jackson.map.JsonMappingException.wrapWithPath(JsonMappingException.java:183) ~[jackson-mapper-asl-1.9.13.jar:1.9.13]
at org.codehaus.jackson.map.ser.std.SerializerBase.wrapAndThrow(SerializerBase.java:140) ~[jackson-mapper-asl-1.9.13.jar:1.9.13]
at org.codehaus.jackson.map.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:158) ~[jackson-mapper-asl-1.9.13.jar:1.9.13]
at org.codehaus.jackson.map.ser.BeanSerializer.serialize(BeanSerializer.java:112) ~[jackson-mapper-asl-1.9.13.jar:1.9.13]
at org.codehaus.jackson.map.ser.StdSerializerProvider._serializeValue(StdSerializerProvider.java:610) ~[jackson-mapper-asl-1.9.13.jar:1.9.13]
at org.codehaus.jackson.map.ser.StdSerializerProvider.serializeValue(StdSerializerProvider.java:256) ~[jackson-mapper-asl-1.9.13.jar:1.9.13]
at org.codehaus.jackson.map.ObjectMapper._configAndWriteValue(ObjectMapper.java:2575) ~[jackson-mapper-asl-1.9.13.jar:1.9.13]
at org.codehaus.jackson.map.ObjectMapper.writeValueAsString(ObjectMapper.java:2097) ~[jackson-mapper-asl-1.9.13.jar:1.9.13]
tried to add deserializer:
CustomDeserializerFactory deserializerFactory = new CustomDeserializerFactory();
deserializerFactory.addSpecificMapping(LocalDateTime.class, new CustomLocalDateTimeDeserializer());
ObjectMapper mapper = new ObjectMapper();
mapper.setDeserializerProvider(new StdDeserializerProvider(deserializerFactory));
try {
remoteActionDto.setPayload(mapper.writeValueAsString(response));
} catch (IOException e) {
logger.error("Can not convert response to json!", e);
.....
}
the deserializer itself. I does not convert actually, but only proof of concept:
private static class CustomLocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
#Override
public LocalDateTime deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
return new LocalDateTime();
}
}
I found the problem (or actually a colleague of mine did it). It is the most stupid java behaviour I've ever met. The problem was, that the DTO which contained the LocalDateTime field was populated via reflection, and it seems possible to successfully set a value of type String. A class cast exception occurs when you try to use this field (not when it is being set).
public class MyDto {
// trough reflection, the contained object is a java.lang.String
private LocalDateTime myDate;
}
If you ask why this happened - because we haven't configured a converter for LocalDateTime, but for DateTime instead. My colleague used LocalDateTime by mistake and Jackson silently deserialized it as a String
I've written a quick test class to check what you've provided. It seems to run fine and output the following:
{"value":[2014,2,24,13,42,44,745]}
Granted, that may not be the exact format you're looking for, but either way, here is the class:
public class JsonSerialization {
public static void main(final String[] args) {
try {
final Response response = new Response();
final ObjectMapper mapper = new ObjectMapper();
final String value = mapper.writeValueAsString(response);
System.out.println(value);
}
catch (final Exception e) {
e.printStackTrace();
}
}
public static class Response {
LocalDateTime value = new LocalDateTime();
public LocalDateTime getValue() {
return this.value;
}
public void setValue(final LocalDateTime value) {
this.value = value;
}
}
}
I guess this raises the questions:
Do you have getters and setters for your LocalDateTime property (registrationDate)?
Are you sure the error is occurring where you think it is occurring? The exception is just the part about Jackson, where does it say the writeValueAsString method is called within your code?
I know this isn't part of your question, but in 1.9.13 of Jackson, you should register custom (de)serializers like so:
SimpleModule module = new SimpleModule("", new Version(1, 0, 0, "");
module.addDeserializer(LocalDateTime.class, new CustomLocalDateTimeDeserializer());
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(module);
Register your mapper with JodaModule module.
mapper.register(new JodaModule())
Or try with JodaMapper:
import com.fasterxml.jackson.datatype.joda.JodaMapper;
public static void main(String args[]){
DateTime dateTime = new DateTime(12353434);
JodaMapper mapper = new JodaMapper();
try {
serializedString = mapper.writeValueAsString(dateTime);
System.out.println(serializedString);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
Console Output:
12353434

Categories

Resources