我试图在我的Spring MVC 3应用程序中返回一个JSON,但它失败了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"])
看起来我可能需要一个自定义序列化器,但我不知道从哪里开始。
答案 0 :(得分:1)
您可以查看here了解更多详情和选项。
基本上,您需要创建Serializer
,例如:
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();
}
}
然后,您可以使用@JsonSerialize
注释您的课程,例如:
@JsonSerialize(using = ItemSerializer.class)
public class Item {
public int id;
public String itemName;
public User owner;
}