Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson fails to serialize Joda DateTimeFormatter

I am trying to return a JSON in my Spring MVC 3 application, but its failing for Joda DateTimeFormatter

com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class org.joda.time.format.DateTimeFormat$StyleFormatter and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: java.util.HashMap["personDay"]->mypackage.PersonDay["dateTimeFormatter"]->org.joda.time.format.DateTimeFormatter["parser"])

It looks like i might need a custom serializer for this, but i am not sure where to begin.

like image 261
Novice User Avatar asked Nov 24 '25 17:11

Novice User


1 Answers

You can take a look here for more details and options.

Basically, you need to create a Serializer, something like:

public class ItemSerializer extends StdSerializer<Item> {
  public ItemSerializer() {
      this(null);
  }
  public ItemSerializer(Class<Item> t) {
      super(t);
  }
  @Override
  public void serialize(Item value, JsonGenerator jgen, SerializerProvider provider) 
    throws IOException, JsonProcessingException {
      jgen.writeStartObject();
      jgen.writeNumberField("id", value.id);
      jgen.writeStringField("itemName", value.itemName);
      jgen.writeNumberField("owner", value.owner.id);
      jgen.writeEndObject();
  }
}

Then you can annotate your class with: @JsonSerialize, something like:

@JsonSerialize(using = ItemSerializer.class)
public class Item {
    public int id;
    public String itemName;
    public User owner;
}
like image 116
dan Avatar answered Nov 27 '25 06:11

dan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!