json格式化日期时间,日期和时间

时间:2018-01-01 16:55:03

标签: java json jackson gson

我有一个包含以下内容的

class MyClass {

    private Date datetime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2018-01-01 11:32:15");

    private Time time = new Time(System.currentTimeMillis());

    private Date date = new Date(System.currentTimeMillis());

    // getters and setters
}

GSON

Gson gson = new Gson();
System.out.println(gson.toJson(myClass));

Gson gsonBuilder = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
System.out.println(gsonBuilder.toJson(myClass));

我得到了

{"datetime":"Jan 1, 2018 11:32:15 AM","time":"04:51:23 PM","date":"Jan 1, 2018 4:51:23 PM"}

{"datetime":"2018-01-01 11:32:15","time":"04:51:23 PM","date":"2018-01-01 16:51:23"}

杰克逊

ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writeValueAsString(myClass));

mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
System.out.println(mapper.writeValueAsString(myClass));

我得到了

{"datetime":1514806335000,"time":"17:01:18","date":1514826078776}

{"datetime":"2018-01-01T11:32:15.000+0000","time":"17:13:52","date":"2018-01-01T17:13:52.224+0000"}

我怎样才能获得

{"datetime":"2018-01-01 11:32:15","time":"16:51:23","date":"2018-01-01"}

我没有绑定任何库,所以如果有一个更合适的JSON库可以完成这项工作,请发表评论。

2 个答案:

答案 0 :(得分:0)

找到答案:

使用Jackson可以注释每个字段

class MyClass {

    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
    public Date datetime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse("2018-01-01 11:32:15");

    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "HH:mm:ss")
    public Time time = new Time(System.currentTimeMillis());

    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
    public Date date = new Date(System.currentTimeMillis());

    MyClass() throws ParseException { }

}

MyClass myClass = new MyClass();

ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.writeValueAsString(myClass));

给你

{"datetime":"2018-01-01 11:32:15","time":"17:21:22","date":"2018-01-01"}

答案 1 :(得分:0)

使用杰克逊,使用

dateTimedate字段添加注释
@JsonFormat
  (shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss")