下面列出了com.fasterxml.jackson.databind.ObjectMapper#addMixIn ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Creates a json string using the swagger object.
*
* @param swaggerObj swagger object
* @return json string using the swagger object
* @throws APIManagementException error while creating swagger json
*/
public static String getSwaggerJsonString(Swagger swaggerObj) throws APIManagementException {
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.enable(SerializationFeature.INDENT_OUTPUT);
//this is to ignore "originalRef" in schema objects
mapper.addMixIn(RefModel.class, IgnoreOriginalRefMixin.class);
mapper.addMixIn(RefProperty.class, IgnoreOriginalRefMixin.class);
mapper.addMixIn(RefPath.class, IgnoreOriginalRefMixin.class);
mapper.addMixIn(RefParameter.class, IgnoreOriginalRefMixin.class);
mapper.addMixIn(RefResponse.class, IgnoreOriginalRefMixin.class);
//this is to ignore "responseSchema" in response schema objects
mapper.addMixIn(Response.class, ResponseSchemaMixin.class);
try {
return new String(mapper.writeValueAsBytes(swaggerObj));
} catch (JsonProcessingException e) {
throw new APIManagementException("Error while generating Swagger json from model", e);
}
}
/**
* Creates a json string using the swagger object.
*
* @param swaggerObj swagger object
* @return json string using the swagger object
* @throws APIManagementException error while creating swagger json
*/
private String getSwaggerJsonString(Swagger swaggerObj) throws APIManagementException {
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.enable(SerializationFeature.INDENT_OUTPUT);
//this is to ignore "originalRef" in schema objects
mapper.addMixIn(RefModel.class, IgnoreOriginalRefMixin.class);
mapper.addMixIn(RefProperty.class, IgnoreOriginalRefMixin.class);
mapper.addMixIn(RefPath.class, IgnoreOriginalRefMixin.class);
mapper.addMixIn(RefParameter.class, IgnoreOriginalRefMixin.class);
mapper.addMixIn(RefResponse.class, IgnoreOriginalRefMixin.class);
//this is to ignore "responseSchema" in response schema objects
mapper.addMixIn(Response.class, ResponseSchemaMixin.class);
try {
return new String(mapper.writeValueAsBytes(swaggerObj));
} catch (JsonProcessingException e) {
throw new APIManagementException("Error while generating Swagger json from model", e);
}
}
private static void configureDefaultApiClient(String apiKey, String opsGenieHost, boolean debug) {
final ApiClient defaultApiClient = Configuration.getDefaultApiClient();
defaultApiClient.setApiKeyPrefix("GenieKey");
defaultApiClient.setApiKey(apiKey);
defaultApiClient.setBasePath(opsGenieHost);
defaultApiClient.setDebugging(debug);
ObjectMapper mapper = defaultApiClient.getJSON().getContext(Object.class);
mapper.addMixIn(Recipient.class, IgnoredIdAndType.class);
mapper.addMixIn(Filter.class, IgnoredType.class);
mapper.addMixIn(TimeRestrictionInterval.class, IgnoredType.class);
mapper.addMixIn(DeprecatedAlertPolicy.class, IgnoredType.class);
mapper.addMixIn(Integration.class, IgnoredType.class);
mapper.addMixIn(BaseIntegrationAction.class, IgnoredIdAndType.class);
mapper.addMixIn(Responder.class, IgnoredType.class);
mapper.addMixIn(Policy.class, IgnoredType.class);
}
@Test
void scaUserDataMixIn() throws JsonProcessingException, JSONException {
// Given
String expected = "{\"id\":\"id\",\"login\":\"login\",\"email\":\"email\",\"pin\":\"pin\",\"scaUserData\":[{\"id\":\"id\",\"scaMethod\":\"EMAIL\",\"methodValue\":\"methodValue\",\"user\":null,\"usesStaticTan\":true,\"staticTan\":\"STATIC TAN\", \"decoupled\":false, \"valid\":false}],\"accountAccesses\":[],\"userRoles\":[],\"branch\":\"branch\",\"blocked\":false,\"systemBlocked\":false}";
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.addMixIn(ScaUserDataTO.class, ScaUserDataMixedIn.class);
UserTO user = getUser();
// When
String result = objectMapper.writeValueAsString(user);
// Then
JSONAssert.assertEquals(result, expected, true);
}
@Test
public void testDeserializationWithTypeInfo01() throws Exception {
OffsetDateTime offsetDateTime = OffsetDateTime.of(2017, 9, 2, 10, 15, 30, 0, ZoneOffset.ofHours(1));
ObjectMapper mapper = createMapper();
mapper.addMixIn(TemporalAccessor.class, MockObjectConfiguration.class);
TemporalAccessor value = mapper.readValue("[\"" + OffsetDateTime.class.getName() + "\",\"2017-09-02T10:15:30+01:00\"]", TemporalAccessor.class);
assertNotNull(value, "The value should not be null.");
assertTrue(value instanceof OffsetDateTime, "The value should be a OffsetDateTime.");
assertEquals(offsetDateTime, value, "The value is not correct.");
}
@Test
public final void givenFieldTypeIsIgnored_whenDtoIsSerialized_thenCorrect() throws JsonParseException, IOException {
final ObjectMapper mapper = new ObjectMapper();
mapper.addMixIn(String[].class, MyMixInForIgnoreType.class);
final MyDtoWithSpecialField dtoObject = new MyDtoWithSpecialField();
dtoObject.setBooleanValue(true);
final String dtoAsString = mapper.writeValueAsString(dtoObject);
assertThat(dtoAsString, containsString("intValue"));
assertThat(dtoAsString, containsString("booleanValue"));
assertThat(dtoAsString, not(containsString("stringValue")));
System.out.println(dtoAsString);
}
@Test
public void whenSerializingUsingMixInAnnotation_thenCorrect() throws JsonProcessingException {
final com.baeldung.jackson.annotation.dtos.Item item = new com.baeldung.jackson.annotation.dtos.Item(1, "book", null);
String result = new ObjectMapper().writeValueAsString(item);
assertThat(result, containsString("owner"));
final ObjectMapper mapper = new ObjectMapper();
mapper.addMixIn(com.baeldung.jackson.annotation.dtos.User.class, MyMixInForIgnoreType.class);
result = mapper.writeValueAsString(item);
assertThat(result, not(containsString("owner")));
}
private static void configureClientObjectMapper(ApiClient defaultApiClient) {
ObjectMapper mapper = defaultApiClient.getJSON().getContext(Object.class);
mapper.addMixIn(Filter.class, IgnoredType.class);
mapper.addMixIn(TimeRestrictionInterval.class, IgnoredType.class);
mapper.addMixIn(Recipient.class, IgnoredType.class);
mapper.addMixIn(DeprecatedAlertPolicy.class, IgnoredType.class);
mapper.addMixIn(Integration.class, IgnoredType.class);
mapper.addMixIn(BaseIntegrationAction.class, IgnoredIntegration.class);
mapper.addMixIn(Policy.class, IgnoredType.class);
mapper.addMixIn(Responder.class, IgnoredType.class);
}
@Test
public void testDeserializationWithTypeInfo01() throws Exception {
OffsetTime offsetTime = OffsetTime.of(10, 15, 30, 0, ZoneOffset.ofHours(1));
ObjectMapper mapper = createMapper();
mapper.addMixIn(TemporalAccessor.class, MockObjectConfiguration.class);
TemporalAccessor value = mapper.readValue("[\"" + OffsetTime.class.getName() + "\",\"10:15:30+01:00\"]", TemporalAccessor.class);
assertNotNull(value);
assertTrue(value instanceof OffsetTime, "The value should be a OffsetTime.");
assertEquals(offsetTime, value);
}
@Before
public void setup() {
mapper = new ObjectMapper();
mapper.addMixIn(Aggregation.class, TypeNameMixin.class);
mapper.registerModule(new Jdk8Module());
mapper.registerSubtypes(new NamedType(Group.class, Group.NAME));
mapper.registerSubtypes(new NamedType(Empty.class, Empty.NAME));
}
@Override
public void setup(Bootstrap<?> bootstrap) {
ObjectMapper om = bootstrap.getObjectMapper();
// for Config
om.addMixIn(SessionStore.class, sessionStoreMixin());
om.addMixIn(Authorizer.class, authorizerMixin());
om.addMixIn(HttpActionAdapter.class, httpActionAdapterMixin());
om.addMixIn(Matcher.class, matcherMixin());
om.addMixIn(SecurityLogic.class, securityLogicMixin());
om.addMixIn(CallbackLogic.class, callbackLogicMixin());
om.addMixIn(LogoutLogic.class, logoutLogicMixin());
// for Clients
om.addMixIn(Client.class, clientMixin());
om.addMixIn(BaseClient.class, baseClientMixin());
// for Clients and Client subsclasses
om.addMixIn(AjaxRequestResolver.class, ajaxRequestResolverMixin());
om.addMixIn(UrlResolver.class, urlResolverMixin());
om.addMixIn(CallbackUrlResolver.class, callbackUrlResolverMixin());
om.addMixIn(AuthorizationGenerator.class,
authorizationGeneratorMixin());
// for Client/BaseClient
om.addMixIn(Authenticator.class, authenticatorMixin());
om.addMixIn(CredentialsExtractor.class, credentialExtractorMixin());
om.addMixIn(ProfileCreator.class, profileCreatorMixin());
// for IndirectClient
om.addMixIn(RedirectActionBuilder.class, redirectActionBuilderMixin());
om.addMixIn(LogoutActionBuilder.class, logoutActionBuilderMixin());
// for some of the Authenticators
om.addMixIn(PasswordEncoder.class, passwordEncoderMixin());
}
@Before
public void setUp() throws MalformedURLException {
Client client = ClientBuilder.newBuilder().register(JacksonFeature.class).build();
target = client.target(URI.create(new URL(base, "resources/test").toExternalForm()));
objectMapper = new ObjectMapper();
objectMapper.addMixIn(TokenResponse.class, MixInExample.class);
}
@Test
public void testDeserializationWithTypeInfo01() throws Exception {
ZonedDateTime zonedDateTime = ZonedDateTime.of(2017, 9, 2, 10, 15, 30, 0, ZoneOffset.ofHours(1));
ObjectMapper mapper = createMapper();
mapper.addMixIn(TemporalAccessor.class, MockObjectConfiguration.class);
TemporalAccessor value = mapper.readValue("[\"" + ZonedDateTime.class.getName() + "\",\"2017-09-02T10:15:30+01:00\"]", TemporalAccessor.class);
assertNotNull(value);
assertTrue(value instanceof ZonedDateTime, "The value should be a ZonedDateTime.");
assertEquals(zonedDateTime, value);
}
@Override
protected void addCustomMixins(final ObjectMapper objectMapper, final QueryRestrictionsBuilder<?, ?, ?> queryRestrictionsBuilder, final QueryRequestBuilder<?, ?, ?> queryRequestBuilder) {
objectMapper.addMixIn(HodQueryRequest.class, HodQueryRequestMixin.class);
objectMapper.addMixIn(queryRequestBuilder.getClass(), HodQueryRequestBuilderMixins.class);
objectMapper.addMixIn(HodQueryRestrictions.class, HodQueryRestrictionsMixin.class);
objectMapper.addMixIn(queryRestrictionsBuilder.getClass(), HodQueryRestrictionsBuilderMixins.class);
}
public static ObjectMapper configure(ObjectMapper objectMapper) {
objectMapper.addMixIn(Span.class, SpanMixin.class);
objectMapper.addMixIn(KeyValue.class, KeyValueMixin.class);
objectMapper.addMixIn(Reference.class, ReferenceMixin.class);
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
return objectMapper;
}
public static void addMixInsForWireMock(ObjectMapper objectMapper) {
objectMapper.addMixIn(StubMapping.class, StubMappingMixIn.class);
objectMapper.addMixIn(RequestPattern.class, RequestPatternMixIn.class);
objectMapper.addMixIn(StringValuePattern.class, StringValuePatternMixIn.class);
objectMapper.addMixIn(ResponseDefinition.class, ResponseDefinitionMixIn.class);
objectMapper.addMixIn(ContentPattern.class, ContentPatternMixIn.class);
objectMapper.addMixIn(LoggedResponse.class, LoggedResponseMixIn.class);
objectMapper.addMixIn(ServeEvent.class, ServeEventMixIn.class);
objectMapper.addMixIn(LoggedRequest.class, LoggedRequestMixIn.class);
}
/**
* @return {@code com.fasterxml.jackson.databind.ObjectWriter} to serialize {@link BufferedIndex} instances
*/
protected ObjectWriter configuredWriter() {
ObjectMapper objectMapper = new ExtendedObjectMapper(new JsonFactory())
.setSerializationInclusion(JsonInclude.Include.NON_EMPTY)
.configure(SerializationFeature.CLOSE_CLOSEABLE, false)
.addMixIn(BufferedIndex.class, BulkableActionMixIn.class);
for (JacksonMixIn mixIn: mixIns) {
objectMapper.addMixIn(mixIn.getTargetClass(), mixIn.getMixInClass());
}
return objectMapper.writerFor(BufferedIndex.class);
}
protected ObjectWriter createConfiguredWriter(List<JacksonMixIn> mixins) {
ObjectMapper objectMapper = createDefaultObjectMapper();
objectMapper.registerModule(new ExtendedLog4j2JsonModule());
if (useAfterburner) {
// com.fasterxml.jackson.module:jackson-module-afterburner required here
new JacksonAfterburnerModuleConfigurer().configure(objectMapper);
}
for (JacksonMixIn mixin : mixins) {
objectMapper.addMixIn(mixin.getTargetClass(), mixin.getMixInClass());
}
ValueResolver valueResolver = createValueResolver();
for (VirtualProperty property : virtualProperties) {
if (!property.isDynamic()) {
property.setValue(valueResolver.resolve(property.getValue()));
}
}
SerializationConfig customConfig = objectMapper.getSerializationConfig()
.with(new JacksonHandlerInstantiator(
virtualProperties,
valueResolver,
virtualPropertyFilters
));
objectMapper.setConfig(customConfig);
return objectMapper.writer(new MinimalPrettyPrinter());
}
public static void registerMixins(ObjectMapper mapper) {
mapper.addMixIn(Token.class, TokenMixIn.class);
mapper.addMixIn(KeyId.class, KeyIdMixIn.class);
}
/**
* Mixins are added to the object mapper in order to
* ignore certain method signatures from serialization
* that are otherwise treated as getters. Each mixin
* implements the appropriate interface as a private
* dummy class and is annotated with JsonIgnore elements
* throughout. This helps us catch errors at compile-time
* when the interface changes.
* @return the prepped object mapper.
*/
@Override
protected ObjectMapper initializeObjectMapper() {
final ObjectMapper mapper = super.initializeObjectMapper();
mapper.addMixIn(RegisteredServiceProxyPolicy.class, RegisteredServiceProxyPolicyMixin.class);
mapper.addMixIn(RegisteredServiceAccessStrategy.class, RegisteredServiceAuthorizationStrategyMixin.class);
mapper.addMixIn(Duration.class, DurationMixin.class);
return mapper;
}