[alibaba/fastjson]LocalDateTime类型格式化不正确!

2025-10-29 706 views
1

` public class JSONTest {

@Test
public void test(){
    Person person = new Person();
    //正常格式化
    person.birthTime = LocalDateTime.now();
    System.out.println(JSON.toJSONStringWithDateFormat(person, JSON.DEFFAULT_DATE_FORMAT));

    //这里修改了日期全局格式, 但是没有生效
    JSON.DEFFAULT_DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";
    System.out.println(JSON.toJSONString(person, SerializerFeature.WriteDateUseDateFormat));

    //java对象直接转Json,也没有按照修改后的格式来
    JSONObject jsonObject = (JSONObject) JSON.toJSON(person);
    System.out.println(jsonObject.toJSONString());

// {"birthTime":"2019-02-28 12:43:24"} // {"birthTime":"2019-02-28T12:43:24.189"} // {"birthTime":"2019-02-28T12:43:24.189"} }

class Person {
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    public LocalDateTime birthTime;

    public LocalDateTime getBirthTime() {
        return birthTime;
    }

    public void setBirthTime(LocalDateTime birthTime) {
        this.birthTime = birthTime;
    }
}

} `

fastjson版本: group: 'com.alibaba', name: 'fastjson', version: '1.2.56'

回答

5

@ JsonFormat 不是fastjson的特性 要使用@JsonField 不过好像也有问题,我提交PR修复了

3

@rmfish implementation group: 'com.alibaba', name: 'fastjson', version: '1.2.58' 第三个测试用例 : java对象直接转为JSONObject, 仍然无法按照要求格式化, jsonObject.toJSONString() 和JSON.toJSONStringWithDateFormat(jsonObject, JSON.DEFFAULT_DATE_FORMAT) 都不可以

3

@wenshao 请问,这个问题以后会修复么