Пример #1
0
 /** 设置转换日期类型的format pattern,如果不设置默认打印Timestamp毫秒数. */
 public void setDateFormat(String pattern) {
   if (StringUtils.isNotBlank(pattern)) {
     DateFormat df = new SimpleDateFormat(pattern);
     mapper.getSerializationConfig().setDateFormat(df);
     mapper.getDeserializationConfig().setDateFormat(df);
   }
 }
Пример #2
0
 public static <T> T getObject(String s, Class<T> clazz) throws IOException {
   ObjectMapper mapper = new ObjectMapper();
   // 跳过未知(无对应)的属性
   mapper.getDeserializationConfig().disable(Feature.FAIL_ON_UNKNOWN_PROPERTIES);
   T obj = mapper.readValue(s, clazz);
   return obj;
 }
Пример #3
0
  @Test
  public void should_init_default_object_factory_mapper() throws Exception {
    doCallRealMethod().when(extractor).initObjectMapperFactory(configMap);
    ObjectMapperFactory actual = extractor.initObjectMapperFactory(configMap);

    assertThat(actual).isNotNull();

    ObjectMapper mapper = actual.getMapper(Integer.class);

    assertThat(mapper).isNotNull();
    assertThat(mapper.getSerializationConfig().getSerializationInclusion())
        .isEqualTo(Inclusion.NON_NULL);
    assertThat(
            mapper
                .getDeserializationConfig()
                .isEnabled(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES))
        .isFalse();
    Collection<AnnotationIntrospector> ais =
        mapper.getSerializationConfig().getAnnotationIntrospector().allIntrospectors();

    assertThat(ais).hasSize(2);
    Iterator<AnnotationIntrospector> iterator = ais.iterator();

    assertThat(iterator.next())
        .isInstanceOfAny(JacksonAnnotationIntrospector.class, JaxbAnnotationIntrospector.class);
    assertThat(iterator.next())
        .isInstanceOfAny(JacksonAnnotationIntrospector.class, JaxbAnnotationIntrospector.class);
  }
Пример #4
0
 public static <T> List<T> getObjects(String s, Class<?> T) throws IOException {
   ObjectMapper mapper = new ObjectMapper();
   mapper
       .getDeserializationConfig()
       .disable(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES);
   List<T> list = mapper.readValue(s, new TypeReference<List<T>>() {});
   return list;
 }
Пример #5
0
 public JpaPortalEventStore() {
   mapper = new ObjectMapper();
   final AnnotationIntrospector pair =
       new AnnotationIntrospector.Pair(
           new JacksonAnnotationIntrospector(), new JaxbAnnotationIntrospector());
   mapper.getDeserializationConfig().withAnnotationIntrospector(pair);
   mapper.getSerializationConfig().withAnnotationIntrospector(pair);
 }
Пример #6
0
 public JsonBinder(Inclusion inclusion) {
   mapper = new ObjectMapper();
   // 设置输出包含的属性
   mapper.getSerializationConfig().setSerializationInclusion(inclusion);
   // 设置输入时忽略JSON字符串中存在而Java对象实际没有的属性
   mapper
       .getDeserializationConfig()
       .set(
           org.codehaus.jackson.map.DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES,
           false);
 }
  @Override
  public ObjectMapper get() {
    ObjectMapper objectMapper = new ObjectMapper();

    // ignore unknown fields (for backwards compatibility)
    objectMapper.getDeserializationConfig().disable(FAIL_ON_UNKNOWN_PROPERTIES);

    // use ISO dates
    objectMapper.getSerializationConfig().disable(WRITE_DATES_AS_TIMESTAMPS);

    // skip fields that are null instead of writing an explicit json null value
    objectMapper.getSerializationConfig().setSerializationInclusion(NON_NULL);

    // disable auto detection of json properties... all properties must be explicit
    objectMapper
        .getDeserializationConfig()
        .disable(DeserializationConfig.Feature.AUTO_DETECT_FIELDS);
    objectMapper.getDeserializationConfig().disable(AUTO_DETECT_SETTERS);
    objectMapper.getSerializationConfig().disable(SerializationConfig.Feature.AUTO_DETECT_FIELDS);
    objectMapper.getSerializationConfig().disable(AUTO_DETECT_GETTERS);
    objectMapper.getSerializationConfig().disable(AUTO_DETECT_IS_GETTERS);

    if (jsonSerializers != null || jsonDeserializers != null) {
      SimpleModule module = new SimpleModule(getClass().getName(), new Version(1, 0, 0, null));
      if (jsonSerializers != null) {
        for (Entry<Class<?>, JsonSerializer<?>> entry : jsonSerializers.entrySet()) {
          addSerializer(module, entry.getKey(), entry.getValue());
        }
      }
      if (jsonDeserializers != null) {
        for (Entry<Class<?>, JsonDeserializer<?>> entry : jsonDeserializers.entrySet()) {
          addDeserializer(module, entry.getKey(), entry.getValue());
        }
      }
      objectMapper.registerModule(module);
    }

    return objectMapper;
  }
Пример #8
0
 protected TypeNameIdResolver createTypeNameIdResolver(boolean forSerialization) {
   Collection<NamedType> subtypes = new ArrayList<NamedType>();
   subtypes.add(new NamedType(MapHolder.class, "mapHolder"));
   subtypes.add(new NamedType(ArrayList.class, "AList"));
   subtypes.add(new NamedType(HashMap.class, "HMap"));
   ObjectMapper mapper = new ObjectMapper();
   return TypeNameIdResolver.construct(
       mapper.getDeserializationConfig(),
       TypeFactory.defaultInstance().constructType(Object.class),
       subtypes,
       forSerialization,
       !forSerialization);
 }
Пример #9
0
  @Override
  public void render(Map<String, ?> map, HttpServletRequest req, HttpServletResponse resp)
      throws Exception {
    AnnotationIntrospector introspector = new JaxbAnnotationIntrospector();
    mapper.getDeserializationConfig().setAnnotationIntrospector(introspector);
    mapper.getSerializationConfig().setAnnotationIntrospector(introspector);

    // resp.setHeader("Content-Type", "text/html; charset=UTF-8"); // "application/json");

    JsonGenerator generator =
        mapper.getJsonFactory().createJsonGenerator(resp.getOutputStream(), JsonEncoding.UTF8);

    ObjectNode json = mapper.valueToTree(map);
    // json.put("success", true);
    mapper.writeTree(generator, json);
    // mapper.writeValue(generator, ret);
    generator.flush();
  }
  @Override
  public void processPacket(Stanza packet) throws NotConnectedException {
    try {
      if (packet instanceof Message) {

        Message msg = (Message) packet;
        logger.info("Task message received from => {}, body => {}", msg.getFrom(), msg.getBody());

        ObjectMapper mapper = new ObjectMapper();
        mapper.getDeserializationConfig().setDateFormat(new SimpleDateFormat("dd-MM-yyyy HH:mm"));

        final TaskNotification task = mapper.readValue(msg.getBody(), TaskNotification.class);

        // Notify related plug-in
        eventBroker.post(LiderConstants.EVENT_TOPICS.TASK_NOTIFICATION_RECEIVED, task);
      }
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
    }
  }
  @Test
  public void auditServiceTestJSON()
      throws WebApplicationException, IOException, JsonParseException {

    deleteIfExists(JsonTestOutputFile);

    DummyAuditLogRetriever dbAuditLogRetriever = new DummyAuditLogRetriever();
    AuditService auditResource = new AuditService();
    auditResource.setAuditLogRetriever(dbAuditLogRetriever);

    DummyHttpHeaders header = new DummyHttpHeaders(MediaType.APPLICATION_JSON_TYPE);

    Response r = auditResource.getAuditLogs("2012-08-08T00", "en_US", header);

    Assert.assertNotNull(r);
    Assert.assertEquals(Status.OK.getStatusCode(), r.getStatus());
    Assert.assertTrue(r.getEntity() instanceof StreamingOutput);

    StreamingOutput so = (StreamingOutput) r.getEntity();

    File of = new File(JsonTestOutputFile);

    OutputStream os = new FileOutputStream(of);
    so.write(os);
    os.close();

    ObjectMapper mapper = null;
    mapper = new ObjectMapper();
    AnnotationIntrospector introspector = new JaxbAnnotationIntrospector();
    mapper.getDeserializationConfig().withAnnotationIntrospector(introspector);

    AuditLogs auditLogs = mapper.readValue(new File(JsonTestOutputFile), AuditLogs.class);

    Assert.assertEquals(100, auditLogs.auditLogs.size());
    deleteIfExists(JsonTestOutputFile);
  }