开发者社区> 问答> 正文

fastjson 2 的ObjectReader 怎么实现?

请问能不能提供一个 实现 ObjectReader 的例子,FastJson2 网上教程太难找了,全是 FastJson1 的教程,然后 com.alibaba.fastjson2.writer 包下的类是不是现在还不能使用,如 ObjectWriterImplLocalDateTime.class

我想解决的问题是,后端接收 LocalDateTime 属性,前端传值:“2022-05-26”,正常,但是传值:“2022-05-26 16:42:11” 就会报错,下面是我写的 配置类 , 学习的路上,能不能提供一个解决方案,琢磨一整天了。

import com.alibaba.fastjson2.JSON; import com.alibaba.fastjson2.JSONException; import com.alibaba.fastjson2.JSONReader; import com.alibaba.fastjson2.JSONWriter; import com.alibaba.fastjson2.reader.ObjectReader; import com.alibaba.fastjson2.support.config.FastJsonConfig; import com.alibaba.fastjson2.support.spring.http.converter.FastJsonHttpMessageConverter; import com.alibaba.fastjson2.writer.ObjectWriter; import org.springframework.context.annotation.Configuration; import org.springframework.http.MediaType; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.lang.reflect.Type; import java.nio.charset.StandardCharsets; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.Collections; import java.util.List;

@Configuration @EnableWebMvc public class MyWebMvcConfigurer implements WebMvcConfigurer {

@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    FastJsonConfig config = new FastJsonConfig();
    
    config.setDateFormat("yyyy-MM-dd HH:mm:ss");
    
    config.setReaderFeatures(JSONReader.Feature.FieldBased, JSONReader.Feature.SupportArrayToBean, JSONReader.Feature.SupportAutoType);
    config.setWriterFeatures(JSONWriter.Feature.WriteMapNullValue, JSONWriter.Feature.WriteNulls);
    
    JSON.register(LocalDateTime.class, MyLocalDateTimeWriter.instance);
    JSON.register(LocalDate.class, MyLocalDateWriter.instance);

    FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
    converter.setFastJsonConfig(config);
    converter.setDefaultCharset(StandardCharsets.UTF_8);
    converter.setSupportedMediaTypes(Collections.singletonList(MediaType.APPLICATION_JSON));
    converters.add(0, converter);
}

}

class MyLocalDateTimeWriter implements ObjectWriter { static MyLocalDateTimeWriter instance = new MyLocalDateTimeWriter();

@Override
public void write(JSONWriter jsonWriter, Object object, Object fieldName, Type fieldType, long features) {
    if (object == null) {
        jsonWriter.writeNull();
        return;
    }
    LocalDateTime dateTime = (LocalDateTime) object;
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    String format = formatter.format(dateTime);
    // 优先使用name
    jsonWriter.writeString(format);
}

}

class MyLocalDateWriter implements ObjectWriter { static MyLocalDateWriter instance = new MyLocalDateWriter();

@Override
public void write(JSONWriter jsonWriter, Object object, Object fieldName, Type fieldType, long features) {
    if (object == null) {
        jsonWriter.writeNull();
        return;
    }
    LocalDateTime dateTime = (LocalDateTime) object;
    LocalDate date = dateTime.toLocalDate();
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    String format = formatter.format(date);
    // 优先使用name
    jsonWriter.writeString(format);
}

}

原提问者GitHub用户yangcanlin

展开
收起
大圣东游 2023-04-21 12:03:28 505 0
3 条回答
写回答
取消 提交回答
  • 值得去的地方都没有捷径

    在 FastJson 2.x 版本中,ObjectReader 具有以下特征:

    ObjectReader 是一个 builder 模式,它提供了一种基于 Fluent API 的方式创建对象,并设置其属性值。 ObjectReader 使用户可以自定义反序列化逻辑,以便更好地控制对象是如何使用序列化值进行构造的。 下面是一个简单的示例,演示如何在 FastJson 2.x 中使用 ObjectReader:

    public class ExampleObject { private String name; private int age; private LocalDate birthDate; private LocalDateTime lastModified; }

    public class ExampleObjectReader { private static final String NAME_FIELD = "name"; private static final String AGE_FIELD = "age"; private static final String BIRTH_DATE_FIELD = "birthDate"; private static final String LAST_MODIFIED_FIELD = "lastModified";

    public static ExampleObject read(JSONObject jsonObject) {
        ExampleObject exampleObject = new ExampleObject();
        
        if (jsonObject.containsKey(NAME_FIELD)) {
            exampleObject.setName(jsonObject.getString(NAME_FIELD));
        }
        
        if (jsonObject.containsKey(AGE_FIELD)) {
            exampleObject.setAge(jsonObject.getIntValue(AGE_FIELD));
        }
        
        if (jsonObject.containsKey(BIRTH_DATE_FIELD)) {
            String birthDateString = jsonObject.getString(BIRTH_DATE_FIELD);
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate birthDate = LocalDate.parse(birthDateString, dateTimeFormatter);
            exampleObject.setBirthDate(birthDate);
        }
        
        if (jsonObject.containsKey(LAST_MODIFIED_FIELD)) {
            String lastModifiedString = jsonObject.getString(LAST_MODIFIED_FIELD);
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            LocalDateTime lastModified = LocalDateTime.parse(lastModifiedString, dateTimeFormatter);
            exampleObject.setLastModified(lastModified);
        }
        
        return exampleObject;
    }
    

    }

    // 测试实际反序列化的代码

    String jsonString = "{"name": "John Doe", "age": 42, "birthDate": "2000-01-01", "lastModified": "2022-05-26 16:42:11"}"; JSONObject jsonObject = JSONObject.parseObject(jsonString); ExampleObject exampleObject = ExampleObjectReader.read(jsonObject); 以上示例展示了如何以更有效和灵活的方式定义自定义反序列化逻辑并处理具有 LocalDateTime 属性的对象。

    至于您提到的问题,您可以使用 FastJson 提供的 SerializerFeature 序列化功能之一:WriteDateUseDateFormat,并在它的日期时间格式中包含一个模式字符变量,以适应您使用的日期时间格式化字符串。您可以在 FastJson 的全局配置中使用此功能,如下所示:

    JSON.DEFAULT_GENERATE_FEATURE |= SerializerFeature.WriteDateUseDateFormat.getMask();

    FastJsonConfig config = new FastJsonConfig(); config.setDateFormat("yyyy-MM-dd HH:mm:ss"); 对于此配置,将会将 LocalDateTime 从本机日期时间格式序列化为字符串,以便在序列化后进行通信。

    2023-04-21 21:13:38
    赞同 展开评论 打赏
  • 2.0.5支持自动识别了,不用自己写ObjectReader/ObjectWriter,你升级试试看 https://github.com/alibaba/fastjson2/releases/tag/2.0.5

    原回答者GitHub用户wenshao

    2023-04-21 14:50:28
    赞同 展开评论 打赏
  • ObjectReader接口readObject增加参数fieldType和fieldName,和fastjson 1.x兼容

    2023-04-21 12:53:13
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载