com.fasterxml.jackson.databind.DeserializationFeature Java Examples

The following examples show how to use com.fasterxml.jackson.databind.DeserializationFeature. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Jackson2ObjectMapperBuilderTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void booleanSetters() {
	ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json()
			.featuresToEnable(MapperFeature.DEFAULT_VIEW_INCLUSION,
					DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,
					SerializationFeature.INDENT_OUTPUT)
			.featuresToDisable(MapperFeature.AUTO_DETECT_FIELDS,
					MapperFeature.AUTO_DETECT_GETTERS,
					MapperFeature.AUTO_DETECT_SETTERS,
					SerializationFeature.FAIL_ON_EMPTY_BEANS).build();
	assertNotNull(objectMapper);
	assertTrue(objectMapper.isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION));
	assertTrue(objectMapper.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES));
	assertFalse(objectMapper.isEnabled(MapperFeature.AUTO_DETECT_FIELDS));
	assertFalse(objectMapper.isEnabled(MapperFeature.AUTO_DETECT_GETTERS));
	assertFalse(objectMapper.isEnabled(MapperFeature.AUTO_DETECT_SETTERS));
	assertTrue(objectMapper.isEnabled(SerializationFeature.INDENT_OUTPUT));
	assertFalse(objectMapper.isEnabled(SerializationFeature.FAIL_ON_EMPTY_BEANS));
}
 
Example #2
Source File: JacksonConfig.java    From syhthems-platform with MIT License 6 votes vote down vote up
@Bean
public Jackson2ObjectMapperBuilderCustomizer customJackson() {
    return builder -> builder
            // 在序列化时将日期转化为时间戳
            .featuresToEnable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
            .featuresToEnable(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS)
            // 在序列化枚举对象时使用toString方法
            .featuresToEnable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING)
            // 在反序列化枚举对象时使用toString方法
            .featuresToEnable(DeserializationFeature.READ_ENUMS_USING_TO_STRING)
            .featuresToEnable(DeserializationFeature.READ_DATE_TIMESTAMPS_AS_NANOSECONDS)
            // 日期和时间格式:"yyyy-MM-dd HH:mm:ss"
            // .simpleDateFormat(BaseConstants.DATETIME_FORMAT)
            .createXmlMapper(false)
            .timeZone("GMT+8:00")
            ;
}
 
Example #3
Source File: StaccatoApplicationInitializer.java    From staccato with Apache License 2.0 6 votes vote down vote up
@Override
public void run(ApplicationArguments args) throws Exception {
    log.info("Initializing Staccato");

    if (!configProps.isIncludeNullFields()) {
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    }
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);

    if (null != stacInitializers && !stacInitializers.isEmpty()) {
        for (StacInitializer stacInitializer : stacInitializers) {
            log.info("Initializer matched: " + stacInitializer.getName());
            stacInitializer.init();
        }
    }

    log.info("Staccato initialization complete. Setting health status to UP.");
    staccatoHealthIndicator.setHealthy(true);
}
 
Example #4
Source File: ObjectMapperResolver.java    From clouditor with Apache License 2.0 6 votes vote down vote up
public static void configureObjectMapper(ObjectMapper mapper) {
  mapper.registerModule(new JavaTimeModule());
  mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
  mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
  mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
  mapper.enable(SerializationFeature.INDENT_OUTPUT);
  mapper.setSerializationInclusion(Include.NON_NULL);
  mapper.setConfig(mapper.getSerializationConfig().withView(ApiOnly.class));

  // add all sub types of CloudAccount
  for (var type : REFLECTIONS_SUBTYPE_SCANNER.getSubTypesOf(CloudAccount.class)) {
    mapper.registerSubtypes(type);
  }

  // set injectable value to null
  var values = new InjectableValues.Std();
  values.addValue("hash", null);

  mapper.setInjectableValues(values);
}
 
Example #5
Source File: BaseContextImpl.java    From invest-openapi-java-sdk with Apache License 2.0 6 votes vote down vote up
public BaseContextImpl(@NotNull final OkHttpClient client,
                       @NotNull final String url,
                       @NotNull final String authToken,
                       @NotNull final Logger logger) {

    this.authToken = authToken;
    this.finalUrl = Objects.requireNonNull(HttpUrl.parse(url))
            .newBuilder()
            .addPathSegment(this.getPath())
            .build();
    this.client = client;
    this.logger = logger;
    this.mapper = new ObjectMapper();

    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.registerModule(new JavaTimeModule());
    mapper.enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS);
}
 
Example #6
Source File: MapperBuilder.java    From qconfig with MIT License 6 votes vote down vote up
private static void configure(ObjectMapper om, Object feature, boolean state) {
    if (feature instanceof SerializationFeature)
        om.configure((SerializationFeature) feature, state);
    else if (feature instanceof DeserializationFeature)
        om.configure((DeserializationFeature) feature, state);
    else if (feature instanceof JsonParser.Feature)
        om.configure((JsonParser.Feature) feature, state);
    else if (feature instanceof JsonGenerator.Feature)
        om.configure((JsonGenerator.Feature) feature, state);
    else if (feature instanceof MapperFeature)
        om.configure((MapperFeature) feature, state);
    else if (feature instanceof Include) {
        if (state) {
            om.setSerializationInclusion((Include) feature);
        }
    }
}
 
Example #7
Source File: JsonUtils.java    From presto with Apache License 2.0 6 votes vote down vote up
public static <T> T parseJson(Path path, Class<T> javaType)
{
    if (!path.isAbsolute()) {
        path = path.toAbsolutePath();
    }

    checkArgument(exists(path), "File does not exist: %s", path);
    checkArgument(isReadable(path), "File is not readable: %s", path);

    try {
        byte[] json = Files.readAllBytes(path);
        ObjectMapper mapper = new ObjectMapperProvider().get()
                .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        return mapper.readValue(json, javaType);
    }
    catch (IOException e) {
        throw new IllegalArgumentException(format("Invalid JSON file '%s' for '%s'", path, javaType), e);
    }
}
 
Example #8
Source File: JacksonObjectMapper.java    From frostmourne with MIT License 6 votes vote down vote up
public static ObjectMapper settingCommonObjectMapper(ObjectMapper objectMapper) {
    objectMapper.setDateFormat(new StdDateFormat());
    objectMapper.setTimeZone(TimeZone.getDefault());

    objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);

    objectMapper.configure(SerializationFeature.INDENT_OUTPUT, false);
    objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);

    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    objectMapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
    objectMapper.configure(MapperFeature.INFER_PROPERTY_MUTATORS, false);
    objectMapper.configure(MapperFeature.ALLOW_FINAL_FIELDS_AS_MUTATORS, false);

    return objectMapper;
}
 
Example #9
Source File: ReportStatusServiceHttpImpl.java    From mantis with Apache License 2.0 6 votes vote down vote up
public ReportStatusServiceHttpImpl(
        MasterMonitor masterMonitor,
        Observable<Observable<Status>> tasksStatusSubject) {
    this.masterMonitor = masterMonitor;
    this.statusObservable = tasksStatusSubject;
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    final MantisPropertiesService mantisPropertiesService = ServiceRegistry.INSTANCE.getPropertiesService();
    this.defaultConnTimeout = Integer.valueOf(mantisPropertiesService.getStringValue("mantis.worker.heartbeat.connection.timeout.ms", "100"));
    this.defaultSocketTimeout = Integer.valueOf(mantisPropertiesService.getStringValue("mantis.worker.heartbeat.socket.timeout.ms", "1000"));
    this.defaultConnMgrTimeout = Integer.valueOf(mantisPropertiesService.getStringValue("mantis.worker.heartbeat.connectionmanager.timeout.ms", "2000"));

    final Metrics metrics = MetricsRegistry.getInstance().registerAndGet(new Metrics.Builder()
            .name("ReportStatusServiceHttpImpl")
            .addCounter("hbConnectionTimeoutCounter")
            .addCounter("hbConnectionRequestTimeoutCounter")
            .addCounter("hbSocketTimeoutCounter")
            .addCounter("workerSentHeartbeats")
            .build());

    this.hbConnectionTimeoutCounter = metrics.getCounter("hbConnectionTimeoutCounter");
    this.hbConnectionRequestTimeoutCounter = metrics.getCounter("hbConnectionRequestTimeoutCounter");
    this.hbSocketTimeoutCounter = metrics.getCounter("hbSocketTimeoutCounter");
    this.workerSentHeartbeats = metrics.getCounter("workerSentHeartbeats");
}
 
Example #10
Source File: VertxJobsService.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
@PostConstruct
void initialize() {
    DatabindCodec.mapper().disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);
    DatabindCodec.mapper().disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);             
    DatabindCodec.mapper().registerModule(new JavaTimeModule());
    DatabindCodec.mapper().findAndRegisterModules();
    
    DatabindCodec.prettyMapper().registerModule(new JavaTimeModule());
    DatabindCodec.prettyMapper().findAndRegisterModules();
    DatabindCodec.prettyMapper().disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);
    DatabindCodec.prettyMapper().disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

    if (providedWebClient.isResolvable()) {
        this.client = providedWebClient.get();
        LOGGER.debug("Using provided web client instance");
    } else {
        final URI jobServiceURL = getJobsServiceUri();
        this.client = WebClient.create(vertx,
                                       new WebClientOptions()
                                               .setDefaultHost(jobServiceURL.getHost())
                                               .setDefaultPort(jobServiceURL.getPort()));
        LOGGER.debug("Creating new instance of web client for host {} and port {}", jobServiceURL.getHost(), jobServiceURL.getPort());
    }
}
 
Example #11
Source File: CommonUtils.java    From aem-component-generator with Apache License 2.0 5 votes vote down vote up
/**
 * Method to map JSON content from given file into given GenerationConfig type.
 *
 * @param jsonDataFile data-config file
 * @return GenerationConfig java class with the mapped content in json file
 */
public static GenerationConfig getComponentData(File jsonDataFile) {
    if (jsonDataFile.exists()) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            return mapper.readValue(jsonDataFile, GenerationConfig.class);
        } catch (IOException e) {
            throw new GeneratorException(String.format("Exception while reading config file. %n %s", e.getMessage()));
        }
    }
    return null;
}
 
Example #12
Source File: RelJsonReader.java    From Quicksql with MIT License 5 votes vote down vote up
public RelNode read(String s) throws IOException {
  lastRel = null;
  final ObjectMapper mapper = new ObjectMapper();
  Map<String, Object> o = mapper
      .configure(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS, true)
      .readValue(s, TYPE_REF);
  @SuppressWarnings("unchecked")
  final List<Map<String, Object>> rels = (List) o.get("rels");
  readRels(rels);
  return lastRel;
}
 
Example #13
Source File: PostmanImporterV21.java    From milkman with MIT License 5 votes vote down vote up
private <T> T readJson(String json, Class<T> type) throws IOException, JsonParseException, JsonMappingException {
	ObjectMapper mapper = new ObjectMapper();
	mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
	mapper.registerModule(new Postman21Module());
	T pmCollection = mapper.readValue(json, type);
	return pmCollection;
}
 
Example #14
Source File: YamlSourceLoader.java    From camel-k-runtime with Apache License 2.0 5 votes vote down vote up
public YamlSourceLoader() {
    YAMLFactory yamlFactory = new YAMLFactory()
        .configure(YAMLGenerator.Feature.MINIMIZE_QUOTES, true)
        .configure(YAMLGenerator.Feature.USE_NATIVE_TYPE_ID, false);

    this.mapper = new ObjectMapper(yamlFactory)
        .registerModule(new YamlModule())
        .setSerializationInclusion(JsonInclude.Include.NON_EMPTY)
        .setPropertyNamingStrategy(PropertyNamingStrategy.KEBAB_CASE)
        .enable(MapperFeature.USE_GETTERS_AS_SETTERS)
        .disable(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS)
        .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
        .enable(SerializationFeature.INDENT_OUTPUT);
}
 
Example #15
Source File: TimedJsonStreamParser.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
public TimedJsonStreamParser(List<TblColRef> cols, MessageParserInfo parserInfo) {
    this.allColumns = cols;
    if (parserInfo != null) {
        this.formatTs = parserInfo.isFormatTs();
        this.tsColName = parserInfo.getTsColName();
        Map<String, String> mapping = parserInfo.getColumnToSourceFieldMapping();
        if (mapping != null && !mapping.isEmpty()) {
            for (String col : mapping.keySet()) {
                if ((mapping.get(col) != null && mapping.get(col).contains(".")) || !col.equals(mapping.get(col))) {
                    columnToSourceFieldMapping.put(col, mapping.get(col).split("\\."));
                }
            }
            logger.info("Using parser field mapping by {}", parserInfo.getColumnToSourceFieldMapping());
        }
        this.tsParser = parserInfo.getTsParser();

        if (!StringUtils.isEmpty(tsParser)) {
            try {
                Class clazz = Class.forName(tsParser);
                Constructor constructor = clazz.getConstructor(MessageParserInfo.class);
                streamTimeParser = (AbstractTimeParser) constructor.newInstance(parserInfo);
            } catch (Exception e) {
                throw new IllegalStateException("Invalid StreamingConfig, tsParser " + tsParser + ", tsPattern "
                        + parserInfo.getTsPattern() + ".", e);
            }
        } else {
            parserInfo.setTsParser("org.apache.kylin.stream.source.kafka.LongTimeParser");
            parserInfo.setTsPattern("MS");
            streamTimeParser = new LongTimeParser(parserInfo);
        }
    }
    mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    mapper.disable(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE);
    mapper.enable(DeserializationFeature.USE_JAVA_ARRAY_FOR_JSON_ARRAY);
    logger.info("TimedJsonStreamParser with formatTs {} tsColName {}", formatTs, tsColName);
}
 
Example #16
Source File: CuratorScheduler.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
JsonInstanceSerializer(Class<T> payloadClass) {
    this.payloadClass = payloadClass;
    this.mapper = new ObjectMapper();

    // to bypass https://issues.apache.org/jira/browse/CURATOR-394
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    this.type = this.mapper.getTypeFactory().constructType(ServiceInstance.class);
}
 
Example #17
Source File: JsonSerializerUtil.java    From scaffold-cloud with MIT License 5 votes vote down vote up
private static Jackson2JsonRedisSerializer serializeConfig() {
    Jackson2JsonRedisSerializer jackson2JsonRedisSerializer =
            new Jackson2JsonRedisSerializer<>(Object.class);
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
    return jackson2JsonRedisSerializer;
}
 
Example #18
Source File: MqConfig.java    From pmq with Apache License 2.0 5 votes vote down vote up
@Bean
@Primary
// @ConditionalOnMissingBean(ObjectMapper.class)
public ObjectMapper jacksonObjectMapper() {
	ObjectMapper objectMapper = new ObjectMapper();
	objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
	objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS"));
	// objectMapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
	objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
	objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
	return objectMapper;
}
 
Example #19
Source File: BaseRestTest.java    From org.hl7.fhir.core with Apache License 2.0 5 votes vote down vote up
public static <T> T retrieveResourceFromResponse(HttpResponse response, Class<T> clazz)
  throws IOException {

  String jsonFromResponse = EntityUtils.toString(response.getEntity());
  ObjectMapper mapper = new ObjectMapper()
    .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
  return mapper.readValue(jsonFromResponse, clazz);
}
 
Example #20
Source File: JsonConfig.java    From pmq with Apache License 2.0 5 votes vote down vote up
@Bean
@Primary
// @ConditionalOnMissingBean(ObjectMapper.class)
public ObjectMapper jacksonObjectMapper() {
	ObjectMapper objectMapper = new ObjectMapper();
	objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
	objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS"));
	// objectMapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
	objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
	objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
	return objectMapper;
}
 
Example #21
Source File: MetricsServer.java    From mantis with Apache License 2.0 5 votes vote down vote up
public MetricsServer(int port, long publishRateInSeconds, Map<String, String> tags) {
    this.port = port;
    this.publishRateInSeconds = publishRateInSeconds;
    this.tags = tags;
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.registerModule(new Jdk8Module());
}
 
Example #22
Source File: JsonCodec.java    From mantis with Apache License 2.0 5 votes vote down vote up
/**
 * Use {@link JacksonCodecs}
 *
 * @param clazz
 */
@Deprecated
public JsonCodec(Class<T> clazz) {
    this.clazz = clazz;
    mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

}
 
Example #23
Source File: CompositeSolutionService.java    From cubeai with Apache License 2.0 5 votes vote down vote up
private void createBluePrintArtifact(String solutionId, BluePrint bluePrint, String path, String userId) throws JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.setSerializationInclusion(Include.NON_NULL);
    // 15. Write Data to bluePrint file and construct the name of the file
    logger.debug("15. Write Data to bluePrint file and construct the name of the file");
    String bluePrintFileName = "BluePrint" + "-" + solutionId + ".json";
    // 16. Convert bluePrint to json
    logger.debug("16. Convert bluePrint to json");
    String bluePrintJson = mapper.writeValueAsString(bluePrint);
    // 17. Create and write details to file
    logger.debug("17. Create and write details to file");
    DEUtil.writeDataToFile(path, bluePrintFileName, bluePrintJson);
    File bluePrintFile = new File(path.concat(bluePrintFileName));
    // 18. Get the TgifArtifact Data
    logger.debug("18. Get the TgifArtifact Data");
    List<Solution> solutions = ummClient.getSolutionsByUuid(solutionId);
    Solution solution = solutions.get(0);
    String nexusUrl = this.addArtifact2Nexus(solution, bluePrintFile);

    List<Artifact> artifacts = ummClient.getArtifacts(solutionId, configurationProperties.getBlueprintArtifactType());

    if (artifacts!=null && artifacts.size()>0) {
        // 24. Update the TgifArtifact which is already exists as BP
        Artifact artifact = artifacts.get(0);
        artifact.setFileSize(bluePrintFile.length());
        artifact.setModifiedDate(Instant.now());
        artifact.setUrl(nexusUrl);
        ummClient.deleteArtifact(artifact.getId());
        ummClient.createArtifact(artifact);
        logger.debug("24. Updated the ArtifactTypeCode BP which is already exists");
    } else {
        this.createArtifact(solutionId, bluePrintFileName, configurationProperties.getBlueprintArtifactType(), nexusUrl, bluePrintFile.length());
        logger.debug("Successfully created the artifact for the BluePrint for the solution : " + solutionId);
    }
}
 
Example #24
Source File: DataDroppedPayloadSetter.java    From mantis with Apache License 2.0 5 votes vote down vote up
DataDroppedPayloadSetter(Heartbeat heartbeat) {
    this.heartbeat = heartbeat;
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    executor = new ScheduledThreadPoolExecutor(1);
    Metrics m = new Metrics.Builder()
            .name(DATA_DROP_METRIC_GROUP)
            .addGauge(DROP_COUNT)
            .addGauge(ON_NEXT_COUNT)
            .build();
    m = MetricsRegistry.getInstance().registerAndGet(m);
    dropCountGauge = m.getGauge(DROP_COUNT);
    onNextCountGauge = m.getGauge(ON_NEXT_COUNT);
}
 
Example #25
Source File: AppJobClustersMapTest.java    From mantis with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeSerFromString() throws IOException {
    final ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    final String mapping = "{\"version\":\"1\",\"timestamp\":2,\"mappings\":{\"testApp\":{\"__default__\":\"SharedMrePublishEventSource\"}}}";
    AppJobClustersMap appJobClustersMap = mapper.readValue(mapping, AppJobClustersMap.class);
    assertEquals(2, appJobClustersMap.getTimestamp());
    assertEquals("testApp", appJobClustersMap.getStreamJobClusterMap("testApp").getAppName());
    assertEquals("SharedMrePublishEventSource", appJobClustersMap.getStreamJobClusterMap("testApp").getJobCluster("testStream"));
}
 
Example #26
Source File: JsonMapper.java    From spring-cloud-yes with Apache License 2.0 5 votes vote down vote up
private JsonMapper(Include include) {
    mapper = new ObjectMapper();
    // 设置输出时包含属性的风格
    if (include != null) {
        mapper.setSerializationInclusion(include);
    }
    // 设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性
    mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
}
 
Example #27
Source File: KafkaConsumerGroupAnother.java    From kafka_book_demo with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException {
    String[] agrs = {"--describe", "--bootstrap-server",
            "localhost:9092", "--group", "groupIdMonitor"};
    ConsumerGroupCommand.ConsumerGroupCommandOptions options =
            new ConsumerGroupCommand.ConsumerGroupCommandOptions(agrs);
    ConsumerGroupCommand.ConsumerGroupService kafkaConsumerGroupService =
            new ConsumerGroupCommand.ConsumerGroupService(options);

    ObjectMapper mapper = new ObjectMapper();
    //1. 使用jackson-module-scala_2.11
    mapper.registerModule(new DefaultScalaModule());
    //2. 反序列化时忽略对象不存在的属性
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,
            false);
    //3. 将Scala对象序列化成JSON字符串
    //这里原本会有权限问题,通过序列化绕过
    String source = mapper.writeValueAsString(kafkaConsumerGroupService.
            collectGroupOffsets()._2.get());
    //4. 将JSON字符串反序列化成Java对象
    List<PartitionAssignmentStateAnother> target = mapper.readValue(source,
            getCollectionType(mapper,List.class,
                    PartitionAssignmentStateAnother.class));
    //5. 排序
    target.sort((o1, o2) -> o1.getPartition() - o2.getPartition());
    //6. 打印
    printPasList(target);
}
 
Example #28
Source File: MappingJackson2MessageConverterTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void defaultConstructor() {
	MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();
	assertThat(converter.getSupportedMimeTypes(),
			contains(new MimeType("application", "json", StandardCharsets.UTF_8)));
	assertFalse(converter.getObjectMapper().getDeserializationConfig()
			.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES));
}
 
Example #29
Source File: Jackson2ObjectMapperBuilder.java    From java-technology-stack with MIT License 5 votes vote down vote up
private void customizeDefaultFeatures(ObjectMapper objectMapper) {
	if (!this.features.containsKey(MapperFeature.DEFAULT_VIEW_INCLUSION)) {
		configureFeature(objectMapper, MapperFeature.DEFAULT_VIEW_INCLUSION, false);
	}
	if (!this.features.containsKey(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)) {
		configureFeature(objectMapper, DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
	}
}
 
Example #30
Source File: JsonConfig.java    From pmq with Apache License 2.0 5 votes vote down vote up
@Bean
@Primary
// @ConditionalOnMissingBean(ObjectMapper.class)
public ObjectMapper jacksonObjectMapper() {
	ObjectMapper objectMapper = new ObjectMapper();
	objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
	objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS"));
	// objectMapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
	objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
	objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
	return objectMapper;
}