$show=/label

Joda Datetime Jackson DeSerialization - @JsonDeserialize

SHARE:

A quick guide to DeSerialize the Joda DateTime fields from Joda api using Jackson json to Object. Build custom deserializer with @JsonDeserialize to fix MismatchedInputException: Cannot construct an instance of `org.joda.time.DateTime`.

1. Introduction


In this tutorial, You'll learn how to deserialize the Joda DateTime object when working with Jackson JSON to Object conversion java 8.

Jackson String JSON to Object

Jackson API @JsonDeserialize annotation is to use for the custom deserializer and also is to parse the dates using " com.fasterxml.jackson.databind.deser.std.StdDeserializer<DateTime>" class from to Joda API datetime to String.


Joda Datetime Jackson DeSerialization - JSON to Object @JsonDeserialize





2. Example Joda DateTime Fields with Jackson

First, let us write a simple example that tries to convert book json to Book objects using Jackson api.

Jackson JSON to Object @JsonDeserialize

Book.java


Observe the below code where it has int, String fields. And also it has DateTime of Joda API to store the book released time.


package com.javaprogramto.jackson.datetime;

import org.joda.time.DateTime;

public class Book {

    private int id;
    private String title;
    private int pages;
    private DateTime timeReleased;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public int getPages() {
        return pages;
    }

    public void setPages(int pages) {
        this.pages = pages;
    }

    public DateTime getTimeReleased() {
        return timeReleased;
    }

    public void setTimeReleased(DateTime timeReleased) {
        this.timeReleased = timeReleased;
    }

    @Override    
public String toString() {
        return "Book{" +
                "id=" + id +
                ", title='" + title + '\'' +
                ", pages=" + pages +
                ", timeReleased=" + timeReleased +
                '}';
    }
}



book.json


{
  "id": "100",
  "title": "Java Program To Blog",
  "pages": "500",
  "timeReleased": "2019-11-09"}


JSON to Book Object using Jackon


package com.javaprogramto.jackson.datetime;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.File;
import java.io.IOException;

public class BookToString {

    public static void main(String[] args) {

        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);


        try {
            // JSON file to Java object            Book book = mapper.readValue(new File("/Users/venkateshn/Documents/VenkY/blog/workspace/CoreJava/src/main/resources/book.json"), Book.class);

            System.out.println("book object from josn : " + book);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Output:

 com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `org.joda.time.DateTime` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('2019-11-09')

 at [Source: (File); line: 5, column: 19] (through reference chain: com.javaprogramto.jackson.datetime.Book["timeReleased"])

 at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:63)

 at com.fasterxml.jackson.databind.DeserializationContext.reportInputMismatch(DeserializationContext.java:1451)

 at com.fasterxml.jackson.databind.DeserializationContext.handleMissingInstantiator(DeserializationContext.java:1081)

 at com.fasterxml.jackson.databind.deser.ValueInstantiator._createFromStringFallbacks(ValueInstantiator.java:371)

 at com.fasterxml.jackson.databind.deser.std.StdValueInstantiator.createFromString(StdValueInstantiator.java:323)

 at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromString(BeanDeserializerBase.java:1396)

 at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeOther(BeanDeserializer.java:176)

 at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:166)

 at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:129)

 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._readMapAndClose(ObjectMapper.java:4482)

 at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3299)

 at com.javaprogramto.jackson.datetime.BookToString.main(BookToString.java:17)


It is failed because Jackson does not know how to parse the Joda DateTime properly.

Java 8 new Date-Time API

If you remove the timeReleased field then it generates the output as expected.

[book object from josn : Book{id=100, title='Java Program To Blog', pages=500}]

3. Custom DeSerializer for Joda DateTime Fields

Altogether now, Let us build the custom deserializer to covert String to DateTime format and map to timeReleased field.

@JsonDeserialize(using = CustomDateTimeDeserializer.class)
private DateTime timeReleased;

Custom Deserializer:

Next, Use StdDeserializer interface and override deserialize() method.

package com.javaprogramto.jackson.datetime;


import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

import java.io.IOException;

public class CustomDateTimeDeserializer extends StdDeserializer<DateTime> {
    private static final long serialVersionUID = 1L;
    private static DateTimeFormatter format = DateTimeFormat.forPattern("yyyy-MM-dd");

    public CustomDateTimeDeserializer() {
        this(null);
    }

    public CustomDateTimeDeserializer(Class<DateTime> t) {
        super(t);
    }

    @Override    public DateTime deserialize(JsonParser parser, DeserializationContext context)
            throws IOException, JsonProcessingException {

        String date = parser.getText();

        return format.parseDateTime(date);

    }
}

Output:

[book object from josn : Book{id=100, title='Java Program To Blog', pages=500, timeReleased=2019-11-09T00:00:00.000+05:30}]

4. Conclusion


In this article, You've seen how to deserialize the Joda DateTime in Jackson API.

All the code is shown in this article is over GitHub.

You can download the project directly and can run in your local without any errors.



If you have any queries please post in the comment section.

COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,16,Arrays,7,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,5,Collections,22,Collector,1,Command Line,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,81,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,4,Dictionary,1,Difference,1,Download,1,Eclipse,2,Efficiently,1,Error,1,Errors,1,Exception,1,Exceptions,3,Fast,1,Files,9,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,4,Grant,1,Grep,1,HashMap,1,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,5,Iterate,2,Jackson API,3,Java,29,Java 10,1,Java 11,5,Java 12,5,Java 13,2,Java 14,2,Java 8,66,Java 8 Difference,2,Java 8 Stream Conversions,2,java 8 Stream Examples,3,Java 9,1,Java Conversions,11,Java Design Patterns,1,Java Files,1,Java Program,2,Java Programs,65,java.lang,5,java.util. function,1,jQuery,1,Kotlin,10,Kotlin Conversions,3,Kotlin Programs,6,Lambda,1,lang,29,Leap Year,1,live updates,1,Logging,1,Mac OS,2,Math,1,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,1,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,21,String,58,String Programs,9,String Revese,1,Swing,1,System,1,Tags,1,Threads,10,Tomcat,1,Tomcat 8,1,Troubleshoot,16,Unix,2,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Joda Datetime Jackson DeSerialization - @JsonDeserialize
Joda Datetime Jackson DeSerialization - @JsonDeserialize
A quick guide to DeSerialize the Joda DateTime fields from Joda api using Jackson json to Object. Build custom deserializer with @JsonDeserialize to fix MismatchedInputException: Cannot construct an instance of `org.joda.time.DateTime`.
https://1.bp.blogspot.com/-1C_xdS-LqzY/XsFXhYhR68I/AAAAAAAACvY/5EbTqE8c6pEA_XZaeRntT8753LoBg4bIgCLcBGAsYHQ/s640/Joda%2BDatetime%2BJackson%2BDeSerialization%2B-%2BJSON%2Bto%2BObject%2B%2540JsonDeserialize-min.png
https://1.bp.blogspot.com/-1C_xdS-LqzY/XsFXhYhR68I/AAAAAAAACvY/5EbTqE8c6pEA_XZaeRntT8753LoBg4bIgCLcBGAsYHQ/s72-c/Joda%2BDatetime%2BJackson%2BDeSerialization%2B-%2BJSON%2Bto%2BObject%2B%2540JsonDeserialize-min.png
JavaProgramTo.com
https://www.javaprogramto.com/2020/05/joda-datetime-jackson-deserialization.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2020/05/joda-datetime-jackson-deserialization.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content