3

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.

Novice User
  • 3,552
  • 6
  • 31
  • 56

1 Answers1

1

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;
}
dan
  • 13,132
  • 3
  • 38
  • 49