【问题标题】:Rest Json Jackson Mapper Custom Object MapperRest Json Jackson Mapper 自定义对象映射器
【发布时间】:2015-12-23 10:51:43
【问题描述】:

我在使用 Jackson Json 映射器时遇到问题,我不知道如何解决。

我有一个 Spring MVC Rest 应用程序,并且使用 Jackson 将端点转换为 Json。

一些结果对象包含我想在转换之前篡改的类型。

更具体地说,结果对象可能如下所示。

ResultObject
    - getDoubleMap() : DoubleMap
        - getDoubleEntries() : List<DoubleEntry>
        - toMap() : Map<String, Double>

我想要做的是不让 Jackson 转换 DoubleMap 实例,而是像这样覆盖它

Object someJacksonMapInterceptor(Object object) {
    if(object instanceof DoubleMap) {
        return ((DoubleMap) object).toMap();
    }
    return object;
}

我已经折磨了谷歌很长一段时间,而不是一个简单的解决方案。希望有人能给点建议。

非常感谢。

【问题讨论】:

    标签: spring rest model-view-controller jackson


    【解决方案1】:

    在一个应用程序中,我们正在自定义取消实现日期,也许您可​​以将其用于自定义取消实现。

    public class VitalSign {
    
        public static final String DATE_FORMAT1 = "yyyy-MM-dd'T'HH:mm:ssZ";
        public static final String DATE_FORMAT2 = "yyyy-MM-dd'T'HH:mm:ss";
        //public static final String DATE_FORMAT3 = "yyyy-MM-dd'T'HH:mm:ssTDZ";
        public static final String DATE_FORMAT4 = "MMM dd, yyyy h:mm:ss aa";
    
    
        @NotNull
        @Column(name = "observed")
        @Temporal(TemporalType.TIMESTAMP)
        @DateTimeFormat(style = "M-")
        @JsonDeserialize(using = CustomJsonDateDeserializer.class)
        private Date timestamp;
    
    
    
        public static class CustomJsonDateDeserializer extends JsonDeserializer<Date> {
    
    
            public CustomJsonDateDeserializer() {
                super();            
            }
    
            @Override
            public Date deserialize(JsonParser jsonparser, DeserializationContext deserializationcontext) throws IOException, JsonProcessingException {
    
                SimpleDateFormat[] formats = { new SimpleDateFormat(DATE_FORMAT1), new SimpleDateFormat(DATE_FORMAT2), new SimpleDateFormat(DATE_FORMAT4, Locale.US) };
                String date = jsonparser.getText();
                for (SimpleDateFormat format : formats) {
                    try {
                        return format.parse(date);
                    } catch (ParseException e) {
                    }               
                }
                throw new RuntimeException("Unparseable date " + date);
    
            }
    
        }
    }
    

    【讨论】:

      【解决方案2】:

      对于序列化,您只需使用 @JsonValue 注释您的 toMap() 方法。对于反序列化,如果您有一个静态工厂来从 Map&lt;String, Double&gt; 创建一个 DoubleMap,您可以使用 @JsonCreator 对其进行注释。

      private final ObjectMapper mapper = new ObjectMapper();
      
      @Test
      public void serialize_doublemap() throws Exception {
          DoubleMap map = new DoubleMap();
          map.put("red", 0.5);
          map.put("orange", 0.7);
          assertThat(mapper.writeValueAsString(map), equivalentTo("{ red: 0.5, orange: 0.7 }"));
      }
      
      @Test
      public void deserialize_doublemap() throws Exception {
          assertThat(mapper.readValue("{ \"red\": 0.5, \"orange\": 0.7 }", DoubleMap.class).toMap(),
                  equalTo(ImmutableMap.of("red", 0.5, "orange", 0.7)));
      }
      
      public static class DoubleMap {
          public List<DoubleEntry> entries = new ArrayList<>();
      
          public void put(String label, double value) {
              entries.add(new DoubleEntry(label, value));
          }
      
          @JsonCreator
          public static DoubleMap fromJson(Map<String, Double> input) {
              DoubleMap map = new DoubleMap();
              input.forEach(map::put);
              return map;
          }
      
          public List<DoubleEntry> getDoubleEntries() {
              return entries;
          }
      
          @JsonValue
          public Map<String, Double> toMap() {
              return entries.stream().collect(Collectors.toMap(e -> e.label, e -> e.value));
          }
      }
      
      public static final class DoubleEntry {
          public final String label;
          public final double value;
      
          public DoubleEntry(String label, double value) {
              this.label = label;
              this.value = value;
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2012-07-08
        • 2021-05-02
        • 1970-01-01
        • 2023-04-06
        • 1970-01-01
        • 2012-12-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多