public ObjectMapper objectMapper() {
   objMapper.enable(SerializationFeature.INDENT_OUTPUT);
   objMapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
   objMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
   objMapper.registerModule(new JSR310Module());
   return objMapper;
 }
示例#2
0
 @Override
 public void afterPropertiesSet() throws Exception {
   mapper = new ObjectMapper();
   mapper.setSerializationInclusion(Include.NON_NULL);
   // 设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性
   mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
   startReciver();
 }
 @Bean
 @Primary
 public ObjectMapper objectMapper() {
   ObjectMapper mapper = new ObjectMapper();
   mapper.registerModule(new JodaModule());
   mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
   mapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
   return mapper;
 }
 @Bean
 public ObjectMapper objectMapper() {
   final ObjectMapper objectMapper = new ObjectMapper();
   objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
   objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
   objectMapper.setDateFormat(new ISO8601DateFormat());
   objectMapper.registerModule(new JodaModule());
   return objectMapper;
 }
示例#5
0
 public JsonMapper(Include include) {
   mapper = new ObjectMapper();
   // 设置输出时包含属性的风格
   if (include != null) {
     mapper.setSerializationInclusion(include);
   }
   // 设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性
   mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
 }
示例#6
0
  static {
    mapper = new ObjectMapper();
    // 设置ObjectMapper只序列化非null的属性,这样可以节省流量
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

    // disable掉FAIL_ON_UNKNOWN_PROPERTIES属性,增强容错性;因为现在有从客户端发json到服务端,在服务端反解的情况了,
    // 所以要加上这个容错选项。

    mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
  }
  @RequestMapping("/vehicleInfo")
  public @ResponseBody VehicleInfo vehicleInfo() throws Exception {

    String json = new String((byte[]) rabbitTemplate.receiveAndConvert(queueName));

    ObjectMapper mapper = new ObjectMapper();
    mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

    return mapper.readValue(json, VehicleInfo.class);
  }
示例#8
0
  @Test
  public void whenSerializingJava8Date_thenCorrect() throws JsonProcessingException {
    final LocalDateTime date = LocalDateTime.of(2014, 12, 20, 2, 30);

    final ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new JSR310Module());
    mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

    final String result = mapper.writeValueAsString(date);
    assertThat(result, containsString("2014-12-20T02:30"));
  }
 public static DeviceSensors fromJson(String json) {
   try {
     ObjectMapper mapper = new ObjectMapper();
     mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
     DeviceSensors deviceSensors = mapper.readValue(json, DeviceSensors.class);
     return deviceSensors;
   } catch (Exception ex) {
     ex.printStackTrace();
   }
   return null;
 }
示例#10
0
  @Test
  public void whenSerializingJodaTime_thenCorrect() throws JsonProcessingException {
    final DateTime date = new DateTime(2014, 12, 20, 2, 30, DateTimeZone.forID("Europe/London"));

    final ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new JodaModule());
    mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

    final String result = mapper.writeValueAsString(date);
    assertThat(result, containsString("2014-12-20T02:30:00.000Z"));
  }
 public String toString() {
   ObjectMapper mapper = new ObjectMapper();
   mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
   String jsonInString;
   try {
     jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(this);
     return jsonInString;
   } catch (JsonProcessingException e) {
     // TODO Auto-generated catch block
     return null;
   }
 }
  /**
   * Create metadata parsing Jenkins update center file.
   *
   * @param data .json or .json.html file served from update center.
   */
  public static UpdateCenterMetadata parse(File data) throws IOException {
    BufferedReader r = new BufferedReader(new FileReader(data));
    r.readLine(); // the first line is preamble
    String json = r.readLine(); // the 2nd line is the actual JSON
    r.readLine(); // the third line is postamble

    ObjectMapper om = new ObjectMapper();
    om.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    UpdateCenterMetadata v = om.readValue(json, UpdateCenterMetadata.class);
    v.init();
    return v;
  }
示例#13
0
 protected RestResource() {
   /*
    * Jackson is serializing java.util.Date (coming out of MongoDB for example) as UNIX epoch by default.
    * Make it write ISO8601 instead.
    * TODO THIS IS EXTREMELY WRONG AND WILL LEAD TO BUGS. NEED TO HAVE IT INJECTED ONCE, AND THEN REUSED (see ObjectMapperProvider)
    * but everyone and their grandmother are using this directly in resource objects instead of relying on Jackson :(
    */
   objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
   objectMapper.setPropertyNamingStrategy(
       PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
   objectMapper.registerModule(new JodaModule());
   objectMapper.registerModule(new GuavaModule());
 }
    /*
     * (non-Javadoc)
     * @see org.springframework.beans.factory.config.BeanPostProcessor#postProcessAfterInitialization(java.lang.Object, java.lang.String)
     */
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName)
        throws BeansException {

      if (!HAL_OBJECT_MAPPER_BEAN_NAME.equals(beanName)) {
        return bean;
      }

      ObjectMapper mapper = (ObjectMapper) bean;
      mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

      return mapper;
    }
 @JsonIgnore
 public String toJson() {
   String jsonData = null;
   try {
     ObjectMapper mapper = new ObjectMapper();
     mapper.enable(SerializationFeature.INDENT_OUTPUT);
     mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
     jsonData = mapper.writeValueAsString(this);
   } catch (Exception ex) {
     ex.printStackTrace();
   }
   return jsonData;
 }
示例#16
0
  static {
    final SimpleModule module =
        new SimpleModule("SwfModule", new Version(1, 0, 0, null, null, null))
            .addSerializer(Date.class, new EpochSecondsDateSerializer())
            .addDeserializer(Date.class, new EpochSecondsDateDeserializer());
    mapper.registerModule(module);
    mapper.setDateFormat(new EpochSecondsDateFormat());
    mapper.addMixInAnnotations(SimpleWorkflowMessage.class, BindingMixIn.class);
    mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
    mapper.disable(MapperFeature.AUTO_DETECT_IS_GETTERS);
    mapper.setVisibilityChecker(
        new VisibilityChecker.Std(VisibilityChecker.Std.class.getAnnotation(JsonAutoDetect.class)) {
          private static final long serialVersionUID = 1L;

          @Override
          public boolean isSetterVisible(final Method m) {
            return !(m.getParameterCount() == 1 && m.getParameterTypes()[0].isEnum())
                && super.isSetterVisible(m);
          }
        });
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
  }
  @Override
  protected HashMap<String, DownloadedImages> doInBackground(List<String>... lists) {
    DownloadedImages downloadedImage;
    int totalNumberOfPhotos;
    try {
      List<String> photoIds = lists[0];
      String photoSizesResult = "", url;
      totalNumberOfPhotos =
          DataManager.getInstance().getReceivedPhotos().getReceivedPhoto().getPhotos().size();
      for (int i = 0; i < photoIds.size(); i++) {

        String currentPhotoId = photoIds.get(i);
        url = String.format(FlickrURL.flickr_photos_getSizes, Constants.API_KEY, currentPhotoId);

        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();

        int statusCode = connection.getResponseCode();
        if (statusCode == HttpURLConnection.HTTP_OK) {
          photoSizesResult = Utility.convertInputStreamToString(connection.getInputStream());
        }
        connection.disconnect();

        ObjectMapper mapper = new ObjectMapper();
        mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        photoSizesResult = photoSizesResult.replace("jsonFlickrApi(", "").replace(")", "");
        ResponsePhotoSizes photoSizeResponse =
            mapper.readValue(photoSizesResult, ResponsePhotoSizes.class);
        List<ResponsePhotoSizes.Sizes.Size> photoSizes =
            photoSizeResponse.getReceivedPhotoSize().getSizes();

        String thumbnailURL = photoSizes.get(2).getSource();
        String mediumURL = photoSizes.get(5).getSource();

        InputStream inputStreamThumbnail = null, inputStreamMedium = null;
        inputStreamThumbnail = new URL(thumbnailURL).openStream();
        inputStreamMedium = new URL(mediumURL).openStream();
        Bitmap bitmapThumbnail = BitmapFactory.decodeStream(inputStreamThumbnail);
        Bitmap bitmapMedium = BitmapFactory.decodeStream(inputStreamMedium);

        publishProgress(DataManager.startIndex + i, totalNumberOfPhotos);
        downloadedImage = new DownloadedImages();
        downloadedImage.setImage(
            new DownloadedImages.ImageDetails(currentPhotoId, bitmapThumbnail, bitmapMedium));
        downloadedImagesHashMap.put(currentPhotoId, downloadedImage);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return downloadedImagesHashMap;
  }
  // [Issue#28]: ObjectMapper.copy()
  public void testCopy() throws Exception {
    ObjectMapper m = new ObjectMapper();
    assertTrue(m.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES));
    m.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    assertFalse(m.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES));
    InjectableValues inj = new InjectableValues.Std();
    m.setInjectableValues(inj);
    assertFalse(m.isEnabled(JsonParser.Feature.ALLOW_COMMENTS));
    m.enable(JsonParser.Feature.ALLOW_COMMENTS);
    assertTrue(m.isEnabled(JsonParser.Feature.ALLOW_COMMENTS));

    // // First: verify that handling of features is decoupled:

    ObjectMapper m2 = m.copy();
    assertFalse(m2.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES));
    m2.enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    assertTrue(m2.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES));
    assertSame(inj, m2.getInjectableValues());

    // but should NOT change the original
    assertFalse(m.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES));

    // nor vice versa:
    assertFalse(m.isEnabled(DeserializationFeature.UNWRAP_ROOT_VALUE));
    assertFalse(m2.isEnabled(DeserializationFeature.UNWRAP_ROOT_VALUE));
    m.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
    assertTrue(m.isEnabled(DeserializationFeature.UNWRAP_ROOT_VALUE));
    assertFalse(m2.isEnabled(DeserializationFeature.UNWRAP_ROOT_VALUE));

    // // Also, underlying JsonFactory instances should be distinct

    assertNotSame(m.getFactory(), m2.getFactory());

    // [Issue#122]: Need to ensure mix-ins are not shared
    assertEquals(0, m.getSerializationConfig().mixInCount());
    assertEquals(0, m2.getSerializationConfig().mixInCount());
    assertEquals(0, m.getDeserializationConfig().mixInCount());
    assertEquals(0, m2.getDeserializationConfig().mixInCount());

    m.addMixIn(String.class, Integer.class);
    assertEquals(1, m.getSerializationConfig().mixInCount());
    assertEquals(0, m2.getSerializationConfig().mixInCount());
    assertEquals(1, m.getDeserializationConfig().mixInCount());
    assertEquals(0, m2.getDeserializationConfig().mixInCount());

    // [Issue#913]: Ensure JsonFactory Features copied
    assertTrue(m2.isEnabled(JsonParser.Feature.ALLOW_COMMENTS));
  }
示例#19
0
 public TaskPersistence() {
   try {
     tasksDirectory = new File(System.getProperty("user.home") + "/.floto/tasks");
     FileUtils.forceMkdir(tasksDirectory);
     long numberOfTasks =
         tasksDirectory.listFiles((FileFilter) FileFilterUtils.directoryFileFilter()).length;
     nextTaskId = new AtomicLong(numberOfTasks + 1);
     objectMapper = new ObjectMapper();
     objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
     objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
     objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
     objectMapper.registerModule(new JSR310Module());
   } catch (IOException e) {
     throw Throwables.propagate(e);
   }
 }
示例#20
0
  @Test
  public void whenSerializingDateToISO8601_thenSerializedToText()
      throws JsonProcessingException, ParseException {
    final SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy hh:mm");
    df.setTimeZone(TimeZone.getTimeZone("UTC"));

    final String toParse = "01-01-1970 02:30";
    final Date date = df.parse(toParse);
    final Event event = new Event("party", date);

    final ObjectMapper mapper = new ObjectMapper();
    mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

    final String result = mapper.writeValueAsString(event);
    assertThat(result, containsString("1970-01-01T02:30:00.000+0000"));
  }
  SchemaDefinition loadExistingSchema(String collectionName) {

    try {
      SolrJsonResponse response =
          SolrSchemaRequest.schema().process(factory.getSolrClient(collectionName));
      if (response != null && response.getNode("schema") != null) {
        ObjectMapper mapper = new ObjectMapper();
        mapper.enable(MapperFeature.AUTO_DETECT_CREATORS);
        mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
        return mapper.readValue(response.getNode("schema").toString(), SchemaDefinition.class);
      }
      return null;
    } catch (SolrServerException e) {
      throw EXCEPTION_TRANSLATOR.translateExceptionIfPossible(new RuntimeException(e));
    } catch (IOException e) {
      throw new InvalidDataAccessResourceUsageException("Failed to load schema definition.", e);
    } catch (SolrException e) {
      throw EXCEPTION_TRANSLATOR.translateExceptionIfPossible(new RuntimeException(e));
    }
  }
 @Inject
 public NodeInfoMapper() {
   this.mapper = new ObjectMapper();
   mapper.registerModule(new JodaModule());
   mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
 }
  @Before
  public void setUp() throws Exception {

    objectMapper = new ObjectMapper();
    objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
  }
示例#24
0
 /**
  * Un-serialize a Json into Module
  *
  * @param module String
  * @return Module
  * @throws IOException
  */
 public static Module unserializeModule(final String module) throws IOException {
   final ObjectMapper mapper = new ObjectMapper();
   mapper.disable(MapperFeature.USE_GETTERS_AS_SETTERS);
   return mapper.readValue(module, Module.class);
 }
示例#25
0
 /**
  * Un-serialize a report with Json
  *
  * @param artifact String
  * @return Artifact
  * @throws IOException
  */
 public static Artifact unserializeArtifact(final String artifact) throws IOException {
   final ObjectMapper mapper = new ObjectMapper();
   mapper.disable(MapperFeature.USE_GETTERS_AS_SETTERS);
   return mapper.readValue(artifact, Artifact.class);
 }
示例#26
0
 /**
  * Un-serialize a report with Json
  *
  * @param license String
  * @return License
  * @throws IOException
  */
 public static License unserializeLicense(final String license) throws IOException {
   final ObjectMapper mapper = new ObjectMapper();
   mapper.disable(MapperFeature.USE_GETTERS_AS_SETTERS);
   return mapper.readValue(license, License.class);
 }
  public void testSingleElementArrayException() throws Exception {
    final ObjectMapper mapper = new ObjectMapper();
    mapper.disable(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS);
    try {
      mapper.readValue("[42]", Integer.class);
      fail(
          "Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
    } catch (JsonMappingException exp) {
      // Exception was thrown correctly
    }
    try {
      mapper.readValue("[42]", Integer.TYPE);
      fail(
          "Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
    } catch (JsonMappingException exp) {
      // Exception was thrown correctly
    }

    try {
      mapper.readValue("[42.273]", Double.class);
      fail(
          "Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
    } catch (JsonMappingException exp) {
      // Exception was thrown correctly
    }
    try {
      mapper.readValue("[42.2723]", Double.TYPE);
      fail(
          "Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
    } catch (JsonMappingException exp) {
      // Exception was thrown correctly
    }

    try {
      mapper.readValue("[42342342342342]", Long.class);
      fail(
          "Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
    } catch (JsonMappingException exp) {
      // Exception was thrown correctly
    }
    try {
      mapper.readValue("[42342342342342342]", Long.TYPE);
      fail(
          "Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
    } catch (JsonMappingException exp) {
      // Exception was thrown correctly
    }

    try {
      mapper.readValue("[42]", Short.class);
      fail(
          "Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
    } catch (JsonMappingException exp) {
      // Exception was thrown correctly
    }
    try {
      mapper.readValue("[42]", Short.TYPE);
      fail(
          "Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
    } catch (JsonMappingException exp) {
      // Exception was thrown correctly
    }

    try {
      mapper.readValue("[327.2323]", Float.class);
      fail(
          "Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
    } catch (JsonMappingException exp) {
      // Exception was thrown correctly
    }
    try {
      mapper.readValue("[82.81902]", Float.TYPE);
      fail(
          "Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
    } catch (JsonMappingException exp) {
      // Exception was thrown correctly
    }

    try {
      mapper.readValue("[22]", Byte.class);
      fail(
          "Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
    } catch (JsonMappingException exp) {
      // Exception was thrown correctly
    }
    try {
      mapper.readValue("[22]", Byte.TYPE);
      fail(
          "Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
    } catch (JsonMappingException exp) {
      // Exception was thrown correctly
    }

    try {
      mapper.readValue("['d']", Character.class);
      fail(
          "Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
    } catch (JsonMappingException exp) {
      // Exception was thrown correctly
    }
    try {
      mapper.readValue("['d']", Character.TYPE);
      fail(
          "Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
    } catch (JsonMappingException exp) {
      // Exception was thrown correctly
    }

    try {
      mapper.readValue("[true]", Boolean.class);
      fail(
          "Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
    } catch (JsonMappingException exp) {
      // Exception was thrown correctly
    }
    try {
      mapper.readValue("[true]", Boolean.TYPE);
      fail(
          "Single value array didn't throw an exception when DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS is disabled");
    } catch (JsonMappingException exp) {
      // Exception was thrown correctly
    }
  }
示例#28
0
 /**
  * Un-serialize a report with Json
  *
  * @param depList String
  * @return DependencyList
  * @throws IOException
  */
 public static DependencyList unserializeDependencyList(final String depList) throws IOException {
   final ObjectMapper mapper = new ObjectMapper();
   mapper.disable(MapperFeature.USE_GETTERS_AS_SETTERS);
   return mapper.readValue(depList, DependencyList.class);
 }
示例#29
0
 /** constructor. */
 public JsonMapper() {
   mapper = new ObjectMapper();
   mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
 }
示例#30
0
 public CrestDataProcessor() {
   mapper = new ObjectMapper();
   mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
   mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
 }