zoukankan      html  css  js  c++  java
  • Spring项目中使用jackson序列化key为对象Map

    1.注入ObjectMapper
    2.注册类HistoricTaskInstance的序列化和反序列化类HistoricTaskInstanceKeySerializer,HistoricTaskInstanceKeyDeSerializer
    3.将新的Modeule注册到ObjectMapper中。
    class A{
       //1.注入ObjectMapper,注意这个ObjectMapper是spring全局的。 @Autowired
    private ObjectMapper objectMapper; public void setKeyProcessor(){    
        SimpleModule sm = new SimpleModule();
        //注册序列化,反序列化类。
        sm.addKeySerializer(HistoricTaskInstance.class,new HistoricTaskInstanceKeySerializer());
        sm.addKeyDeserializer(HistoricTaskInstance.class,new HistoricTaskInstanceKeyDeSerializer());
        //注册到ObjectMapper中。
        objectMapper.registerModule(sm);
     } 
    }

    static class HistoricTaskInstanceKeySerializer extends JsonSerializer<HistoricTaskInstance> {
    private final ObjectMapper objectMapper = new ObjectMapper();
    @Override
    public void serialize(HistoricTaskInstance historicTaskInstance, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
    StringWriter writer = new StringWriter();
    objectMapper.writeValue(writer, historicTaskInstance);
    jsonGenerator.writeFieldName(writer.toString());
    }
    }


    static class SimpleObjectKeyDeSerializer extends KeyDeserializer {
    private final ObjectMapper objectMapper = new ObjectMapper();
    @Override
    public HistoricTaskInstance deserializeKey(String key, DeserializationContext deserializationContext) throws IOException {
    return objectMapper.readValue(key, HistoricTaskInstance.class);
    }
    }

    class HistoricTaskInstance{
      private String name;
    private String address;
    }
     
  • 相关阅读:
    Laravel-RestfulAPI 资源控制器(全面详解)
    Laravel 支付宝SDK在Laravel5的封装
    Laravel 集成 阿里大于 短信接口
    Laravel --进阶篇 (单用户登录)
    Laravel LTS 分割 路由文件的最佳方式
    Laravel -- 实战篇 自制二维码 Simple QrCode
    Laravel 使用 Aliyun OSS 云存储
    Laravel 富文本插件-Ueditor
    Laravel 实战篇
    Laravel 微信开发组件-WeChat 微信支付
  • 原文地址:https://www.cnblogs.com/luoluoshidafu/p/10979018.html
Copyright © 2011-2022 走看看