如何将json日期时间序列化为joda-time

时间:2016-09-20 04:30:36

标签: java json playframework jodatime

这是我从客户端解析有效负载时遇到的异常 无法从字符串值中实例化[simple type,class org.joda.time.DateTime]类型的值(' 2014-06-18 06:26:56-07:00');没有单字符串构造函数/工厂方法

因为自从没有接受字符串日期的joda-time的争论

来自(客户端/网络),模型和控制器的我的json有效负载

有效载荷

[
  {
    "id": 10000000,
    "name": "Dimebad Darrel",
    "duetime": "2014-06-18 06:26:56-07:00",
    "jointime": "2015-04-08 12:47:16-07:00"
  }
]

Customer.class

@Entity
public class Customer implements Serializable, Comparable<Customer>{

    @Id
    private long id;

    private String name;

    @JsonFormat(pattern = "yyyy-MM-ddTHH:mm:ss")
    //@JsonSerialize(using = DateSerializer.class)
    private DateTime duetime;

    @JsonFormat(pattern = "yyyy-MM-ddTHH:mm:ss")
    //@JsonSerialize(using = DateSerializer.class)
    private DateTime jointime;

    public long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public DateTime getDuetime() {
        return duetime;
    }

    public void setDuetime(DateTime duetime) {
        // String startDate = "2013-07-12T18:31:01.000Z";
        // DateTime dt = ISODateTimeFormat.dateTime().parseDateTime(startDate); 
        this.duetime = duetime;
    }

    public DateTime getJointime() {
        return jointime;
    }

    public void setJointime(DateTime jointime) {
        this.jointime = jointime;
    }

    @Override
    public int compareTo(Customer customer) {
        DateTime thisDueDate = customer.getDuetime();
        DateTime otherDueDate = customer.getDuetime();

        if( thisDueDate.isAfter(otherDueDate) )
            return 1;
        else if( thisDueDate.isBefore(otherDueDate) )
            return -1;
        // default equals   
        return 0;
    }

}

CustomerController.class

public class CustomerController extends Controller{

    @Inject
    CustomerService service;

    public Result sortCustomer() {
        try{
            ObjectMapper objectMapper = new ObjectMapper();
            objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

            Json.setObjectMapper(objectMapper);
            String jsonString = request().body().asJson().toString();
            List<Customer> customers = objectMapper.readValue(jsonString,
                            objectMapper.getTypeFactory().constructCollectionType(List.class, Customer.class));

            //service.sort( customers );

            return ok( Json.toJson(customers) );
        }catch(Exception ex ){
            throw new IllegalStateException(ex.getMessage(), ex);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

尝试jackson-datatype-joda

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new JodaModule());