下面列出了怎么用com.fasterxml.jackson.databind.DeserializationFeature的API类实例代码及写法,或者点击链接到github查看源代码。
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);
}
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);
}
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);
}
}
}
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);
}
}
@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());
}
}
@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));
}
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");
}
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;
}
@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")
;
}
@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);
}
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);
}
}
public static JsonDecoder createJsonDecoder() {
// Force Transaction Deserialization to fail if missing expected properties
final ObjectMapper jsonObjectMapper = new ObjectMapper();
jsonObjectMapper.configure(DeserializationFeature.FAIL_ON_NULL_CREATOR_PROPERTIES, true);
jsonObjectMapper.configure(DeserializationFeature.FAIL_ON_MISSING_CREATOR_PROPERTIES, true);
return new JsonDecoder(jsonObjectMapper);
}
public static ObjectMapper createJSONMapper() {
ObjectMapper mapper = new ObjectMapper();
// SerializationFeature for changing how JSON is written
mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
// DeserializationFeature for changing how JSON is read as POJOs:
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);
return mapper;
}
@Bean
public ObjectMapper jsonMapper() {
return new ObjectMapper()
.registerModule(new SchemaSerializationModule())
.registerModule(Event.module())
.registerModule(new JavaTimeModule())
.disable(MapperFeature.DEFAULT_VIEW_INCLUSION)
.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
.disable(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS);
}
@Bean
public Decoder feignDecoder() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, false);
objectMapper.registerModule(new JavaTimeModule());
HttpMessageConverter jacksonConverter = new MappingJackson2HttpMessageConverter(objectMapper);
ObjectFactory<HttpMessageConverters> objectFactory = () -> new HttpMessageConverters(jacksonConverter);
return new ResponseEntityDecoder(new SpringDecoder(objectFactory));
}
private <X> X getSingle(String userURL, Map<String, String> headers, Class<X> type) throws IOException {
HttpGet httpGet = new HttpGet(userURL);
for (Map.Entry<String, String> entry : headers.entrySet()) {
httpGet.addHeader(entry.getKey(), entry.getValue());
}
try (CloseableHttpClient httpClient = HttpClients.createSystem()) {
HttpResponse httpResponse = httpClient.execute(httpGet);
if (null != httpResponse && httpResponse.getStatusLine().getStatusCode() != 200) {
LOGGER.error(httpResponse.toString());
LOGGER.error(EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8));
throw new IllegalStateException(
"An error was returned in the response from the Gitlab API. See the previous log messages for details");
} else if (null != httpResponse) {
LOGGER.debug(httpResponse.toString());
HttpEntity entity = httpResponse.getEntity();
X user = new ObjectMapper()
.configure(DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT, true)
.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true)
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.readValue(IOUtils.toString(entity.getContent(), StandardCharsets.UTF_8), type);
LOGGER.info(type + " received");
return user;
} else {
throw new IOException("No response reveived");
}
}
}
@Test // SPR-12724
public void mimetypeParametrizedConstructor() {
MimeType mimetype = new MimeType("application", "xml", StandardCharsets.UTF_8);
MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter(mimetype);
assertThat(converter.getSupportedMimeTypes(), contains(mimetype));
assertFalse(converter.getObjectMapper().getDeserializationConfig()
.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES));
}
public static ObjectMapper create(BlockAllocator allocator)
{
ObjectMapper objectMapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(Schema.class, new SchemaSerializer());
module.addDeserializer(Schema.class, new SchemaDeserializer());
module.addDeserializer(Block.class, new BlockDeserializer(allocator));
module.addSerializer(Block.class, new BlockSerializer());
//todo provide a block serializer instead of batch serializer but only serialize the batch not the schema.
objectMapper.registerModule(module)
.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
return objectMapper;
}
public static <T> T fromJson(String jsonString, Class<T> clazz) {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.configure(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS, true);
try {
return mapper.readValue(jsonString, clazz);
} catch (IOException e) {
logger.error(e.getMessage(), e);
throw new HyenaServiceException(" result can not converto to Object");
}
}
public static <T> T fromJson(String json, TypeReference<T> typereference) {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.configure(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS, true);
try {
return mapper.readValue(json, typereference);
} catch (IOException e) {
logger.error(e.getMessage(), e);
throw new HyenaServiceException(" result can not converto to Object");
}
}
public static String toJsonString(Object obj) {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
String jsonString = "";
try {
jsonString = mapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
logger.error(e.getMessage(), e);
}
return jsonString;
}
@Inject
public PinotClient(
PinotConfig config,
PinotMetrics metrics,
@ForPinot HttpClient httpClient,
JsonCodec<GetTables> tablesJsonCodec,
JsonCodec<BrokersForTable> brokersForTableJsonCodec,
JsonCodec<TimeBoundary> timeBoundaryJsonCodec,
JsonCodec<BrokerResponseNative> brokerResponseCodec)
{
this.brokersForTableJsonCodec = requireNonNull(brokersForTableJsonCodec, "brokers for table json codec is null");
this.timeBoundaryJsonCodec = requireNonNull(timeBoundaryJsonCodec, "time boundary json codec is null");
this.tablesJsonCodec = requireNonNull(tablesJsonCodec, "json codec is null");
this.schemaJsonCodec = new JsonCodecFactory(() -> new ObjectMapper()
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)).jsonCodec(Schema.class);
this.brokerResponseCodec = requireNonNull(brokerResponseCodec, "brokerResponseCodec is null");
requireNonNull(config, "config is null");
if (config.getControllerUrls() == null || config.getControllerUrls().isEmpty()) {
throw new PinotException(PINOT_INVALID_CONFIGURATION, Optional.empty(), "No pinot controllers specified");
}
this.controllerUrls = config.getControllerUrls();
this.metrics = requireNonNull(metrics, "metrics is null");
this.httpClient = requireNonNull(httpClient, "httpClient is null");
this.brokersForTableCache = CacheBuilder.newBuilder()
.expireAfterWrite(config.getMetadataCacheExpiry().roundTo(TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS)
.build((CacheLoader.from(this::getAllBrokersForTable)));
}
public void getUser() throws Exception {
HttpRequest request = restClient.requestBuilder(
URI.create(userEndpoint + "?name=x"),
Optional.empty()
).GET().build();
HttpResponse<String> response = restClient.send(request);
LOG.info("Response status code: {}", response.statusCode());
LOG.info("Response headers: {}", response.headers());
LOG.info("Response body: {}", response.body());
if (response.statusCode() == 200) {
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
UserVO[] userVO = objectMapper.readValue(response.body(), UserVO[].class);
LOG.info("UserVO: {}", userVO.length);
}
}
public void getUser() throws Exception {
HttpRequest request = restClient.requestBuilder(
URI.create(userEndpoint + "?name=x"),
Optional.empty()
).GET().build();
HttpResponse<String> response = restClient.send(request);
LOG.info("Response status code: {}", response.statusCode());
LOG.info("Response headers: {}", response.headers());
LOG.info("Response body: {}", response.body());
if (response.statusCode() == 200) {
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
UserVO[] userVO = objectMapper.readValue(response.body(), UserVO[].class);
LOG.info("UserVO: {}", userVO.length);
}
}
public void getUser() throws Exception {
HttpRequest request = restClient.requestBuilder(
URI.create(userEndpoint + "?name=x"),
Optional.empty()
).GET().build();
HttpResponse<String> response = restClient.send(request);
LOG.info("Response status code: {}", response.statusCode());
LOG.info("Response headers: {}", response.headers());
LOG.info("Response body: {}", response.body());
if (response.statusCode() == 200) {
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
UserVO[] userVO = objectMapper.readValue(response.body(), UserVO[].class);
LOG.info("UserVO: {}", userVO.length);
}
}
@Test
public void defaultConstructor() {
MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter();
assertThat(converter.getSupportedMimeTypes(),
contains(new MimeType("application", "json")));
assertFalse(converter.getObjectMapper().getDeserializationConfig()
.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES));
}
@Test // SPR-12724
public void mimetypeParametrizedConstructor() {
MimeType mimetype = new MimeType("application", "xml", StandardCharsets.UTF_8);
MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter(mimetype);
assertThat(converter.getSupportedMimeTypes(), contains(mimetype));
assertFalse(converter.getObjectMapper().getDeserializationConfig()
.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES));
}
@Test // SPR-12724
public void mimetypesParametrizedConstructor() {
MimeType jsonMimetype = new MimeType("application", "json", StandardCharsets.UTF_8);
MimeType xmlMimetype = new MimeType("application", "xml", StandardCharsets.UTF_8);
MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter(jsonMimetype, xmlMimetype);
assertThat(converter.getSupportedMimeTypes(), contains(jsonMimetype, xmlMimetype));
assertFalse(converter.getObjectMapper().getDeserializationConfig()
.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES));
}
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);
}
}
@Test
public void defaultProperties() {
ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json().build();
assertNotNull(objectMapper);
assertFalse(objectMapper.isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION));
assertFalse(objectMapper.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES));
assertTrue(objectMapper.isEnabled(MapperFeature.AUTO_DETECT_FIELDS));
assertTrue(objectMapper.isEnabled(MapperFeature.AUTO_DETECT_GETTERS));
assertTrue(objectMapper.isEnabled(MapperFeature.AUTO_DETECT_IS_GETTERS));
assertTrue(objectMapper.isEnabled(MapperFeature.AUTO_DETECT_SETTERS));
assertFalse(objectMapper.isEnabled(SerializationFeature.INDENT_OUTPUT));
assertTrue(objectMapper.isEnabled(SerializationFeature.FAIL_ON_EMPTY_BEANS));
}