下面列出了怎么用com.fasterxml.jackson.annotation.JsonInclude.Include的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);
}
@Test
public void booleanSetters() {
this.factory.setAutoDetectFields(false);
this.factory.setAutoDetectGettersSetters(false);
this.factory.setDefaultViewInclusion(false);
this.factory.setFailOnEmptyBeans(false);
this.factory.setIndentOutput(true);
this.factory.afterPropertiesSet();
ObjectMapper objectMapper = this.factory.getObject();
assertFalse(objectMapper.getSerializationConfig().isEnabled(MapperFeature.AUTO_DETECT_FIELDS));
assertFalse(objectMapper.getDeserializationConfig().isEnabled(MapperFeature.AUTO_DETECT_FIELDS));
assertFalse(objectMapper.getSerializationConfig().isEnabled(MapperFeature.AUTO_DETECT_GETTERS));
assertFalse(objectMapper.getDeserializationConfig().isEnabled(MapperFeature.AUTO_DETECT_SETTERS));
assertFalse(objectMapper.getDeserializationConfig().isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION));
assertFalse(objectMapper.getSerializationConfig().isEnabled(SerializationFeature.FAIL_ON_EMPTY_BEANS));
assertTrue(objectMapper.getSerializationConfig().isEnabled(SerializationFeature.INDENT_OUTPUT));
assertSame(Include.ALWAYS, objectMapper.getSerializationConfig().getSerializationInclusion());
}
@Test
public void booleanSetters() {
this.factory.setAutoDetectFields(false);
this.factory.setAutoDetectGettersSetters(false);
this.factory.setDefaultViewInclusion(false);
this.factory.setFailOnEmptyBeans(false);
this.factory.setIndentOutput(true);
this.factory.afterPropertiesSet();
ObjectMapper objectMapper = this.factory.getObject();
assertFalse(objectMapper.getSerializationConfig().isEnabled(MapperFeature.AUTO_DETECT_FIELDS));
assertFalse(objectMapper.getDeserializationConfig().isEnabled(MapperFeature.AUTO_DETECT_FIELDS));
assertFalse(objectMapper.getSerializationConfig().isEnabled(MapperFeature.AUTO_DETECT_GETTERS));
assertFalse(objectMapper.getDeserializationConfig().isEnabled(MapperFeature.AUTO_DETECT_SETTERS));
assertFalse(objectMapper.getDeserializationConfig().isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION));
assertFalse(objectMapper.getSerializationConfig().isEnabled(SerializationFeature.FAIL_ON_EMPTY_BEANS));
assertTrue(objectMapper.getSerializationConfig().isEnabled(SerializationFeature.INDENT_OUTPUT));
assertSame(Include.ALWAYS, objectMapper.getSerializationConfig().getSerializationInclusion());
}
private void outputGrouped() {
TreeMap<String, Set<String>> grouped = new TreeMap<String, Set<String>>();
for (UnsolvedBindings symbol: unsolved) {
String depended = symbol.getRawName();
String from = leadingNameStripper.stripFilename(symbol.getSourceDisplay());
Set<String> list = grouped.get(depended);
if (list==null) {
list = new HashSet<>();
grouped.put(depended, list);
}
list.add(from);
}
ObjectMapper om = new ObjectMapper();
om.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
om.configure(SerializationFeature.INDENT_OUTPUT, true);
om.setSerializationInclusion(Include.NON_NULL);
try {
om.writerWithDefaultPrettyPrinter().writeValue(new File(outputDir + File.separator + name +"-PotentialExternalDependencies.json"), grouped);
} catch (Exception e) {
e.printStackTrace();
}
}
public static PipelineElementConfiguration defaultConfiguration(final Class<? extends PipelineElement> clazz) {
final ObjectMapper mapper = new ObjectMapper().setSerializationInclusion(Include.NON_DEFAULT);
final PipelineElementConfiguration element = new PipelineElementConfiguration();
element.setClassName(clazz.getCanonicalName());
for(final Class<?> subClazz : clazz.getDeclaredClasses()) {
// We're assuming there's a public static inner class named Configuration if the element needs a configuration.
if(subClazz.getName().endsWith("Configuration")) {
element.setConfigClassName(subClazz.getName());
try {
final Object defaultConfig = subClazz.newInstance();
element.setConfig(mapper.valueToTree(defaultConfig));
} catch(InstantiationException | IllegalAccessException e) {
LOGGER.error("Failed to generate default configuration for " + clazz.getCanonicalName() + "!", e);
}
}
}
return element;
}
@Test
public void booleanSetters() {
this.factory.setAutoDetectFields(false);
this.factory.setAutoDetectGettersSetters(false);
this.factory.setDefaultViewInclusion(false);
this.factory.setFailOnEmptyBeans(false);
this.factory.setIndentOutput(true);
this.factory.afterPropertiesSet();
ObjectMapper objectMapper = this.factory.getObject();
assertFalse(objectMapper.getSerializationConfig().isEnabled(MapperFeature.AUTO_DETECT_FIELDS));
assertFalse(objectMapper.getDeserializationConfig().isEnabled(MapperFeature.AUTO_DETECT_FIELDS));
assertFalse(objectMapper.getSerializationConfig().isEnabled(MapperFeature.AUTO_DETECT_GETTERS));
assertFalse(objectMapper.getDeserializationConfig().isEnabled(MapperFeature.AUTO_DETECT_SETTERS));
assertFalse(objectMapper.getDeserializationConfig().isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION));
assertFalse(objectMapper.getSerializationConfig().isEnabled(SerializationFeature.FAIL_ON_EMPTY_BEANS));
assertTrue(objectMapper.getSerializationConfig().isEnabled(SerializationFeature.INDENT_OUTPUT));
assertSame(Include.ALWAYS, objectMapper.getSerializationConfig().getSerializationInclusion());
}
/**
* 创建只输出初始值被改变的属性到Json字符串的Mapper, 最节约的存储方式,建议在内部接口中使用。
*/
public static JsonMapper nonDefaultMapper() {
if (jsonMapper == null){
jsonMapper = new JsonMapper(Include.NON_DEFAULT);
}
return jsonMapper;
}
@Deprecated
public <E> E deSerialize(String jsonString, Class<E> entityType) {
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(Include.NON_NULL);
try {
if (jsonString != null) {
E entity = mapper.readValue(jsonString, entityType);
return entity;
}
} catch (IOException e) {
logger.error("JSON deserialization exception", e);
}
return null;
}
@Test
public void testKey() throws Exception {
TypeReference<Key<Object>> typeReference = new TypeReference<Key<Object>>() {};
KeyTester.INSTANCE.testSerialize( createWriter( typeReference ) );
KeyTester.INSTANCE.testDeserialize( createReader( typeReference ) );
objectMapper.setSerializationInclusion( Include.NON_NULL );
KeyTester.INSTANCE.testSerializeNonNull( createWriter( typeReference ) );
KeyTester.INSTANCE.testDeserializeNonNull( createReader( typeReference ) );
}
public static ObjectMapper create() {
ObjectMapper mapper = new ObjectMapper();
// forward compatibility for the properties may go away in the future
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL, true);
mapper.setSerializationInclusion(Include.NON_NULL);
return mapper;
}
public static ObjectMapper create() {
ObjectMapper mapper = new ObjectMapper();
// forward compatibility for the properties may go away in the future
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);
mapper.configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL, false);
mapper.setSerializationInclusion(Include.NON_NULL);
return mapper;
}
public <T> Map<String, Object> parseToMap(T object) {
try {
ObjectMapper mapper = mapper().setSerializationInclusion(Include.NON_NULL);
String jsonInString = mapper.writeValueAsString(object);
@SuppressWarnings("unchecked")
Map<String, Object> map = mapper.readValue(jsonInString, Map.class);
return map;
} catch (Exception e) {
log.error(e.getMessage(), e);
return null;
}
}
private JacksonJsonProvider getJacksonProvider() {
JacksonJsonProvider jacksonProvider = new JacksonJsonProvider();
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JSR310Module());
mapper.setSerializationInclusion(Include.NON_EMPTY);
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
jacksonProvider.setMapper(mapper);
return jacksonProvider;
}
public JsonMapper(Include include) {
mapper = new ObjectMapper();
// 设置输出时包含属性的风格
if (include != null) {
mapper.setSerializationInclusion(include);
}
// 设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
}
@Test
public void testWriteNullValues_disabledGlobally() throws Exception {
TestObject ref = new TestObject();
sut.setSerializationInclusion(Include.NON_NULL);
String serialized = sut.writeValueAsString(JsonView.with(ref));
Map<String, Object> obj = sut.readValue(serialized, NonReplacableKeyMap.class);
assertFalse(obj.containsKey("str2"));
}
/**
* 根据Bot返回的Response转换为ResponseEncapsulation,然后序列化
*
* @param response
* Bot返回的Response
* @throws JsonProcessingException
* 抛出异常
* @return String 封装后的ResponseEncapsulation的序列化内容
*/
protected String build(Response response) throws JsonProcessingException {
if (response == null) {
return defaultResponse();
}
Context context = new Context();
if (isIntentRequest() == true) {
context.setIntent(getIntent());
context.setAfterSearchScore(afterSearchScore);
context.setExpectResponses(expectResponses);
}
ResponseBody responseBody = new ResponseBody();
responseBody.setDirectives(directives);
if (response.getCard() != null) {
responseBody.setCard(response.getCard());
}
if (response.getOutputSpeech() != null) {
responseBody.setOutputSpeech(response.getOutputSpeech());
}
if (response.getReprompt() != null) {
responseBody.setReprompt(response.getReprompt());
}
responseBody.setShouldEndSession(shouldEndSession);
responseBody.setNeedDetermine(needDetermine);
responseBody.setExpectSpeech(expectSpeech);
if (response.getResource() != null) {
responseBody.setResource(response.getResource());
}
ResponseEncapsulation responseEncapsulation = new ResponseEncapsulation(context, session, responseBody);
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(Include.NON_NULL);
return mapper.writeValueAsString(responseEncapsulation);
}
@Override
public void serialize( Ref ref, JsonGenerator jgen, SerializerProvider provider ) throws IOException {
jgen.writeStartObject();
boolean includeNull = Include.NON_NULL != provider.getConfig().getDefaultPropertyInclusion().getValueInclusion();
if ( ref.key() != null || includeNull ) {
jgen.writeObjectField( RefConstant.KEY, ref.key() );
}
if ( ref.getValue() != null || includeNull ) {
jgen.writeObjectField( RefConstant.VALUE, ref.getValue() );
}
jgen.writeEndObject();
}
@Test
public void testThrowable() throws IOException {
ThrowableTester.INSTANCE.testSerializeIllegalArgumentException( createWriter( RemoteThrowable.class ) );
ThrowableTester.INSTANCE.testDeserializeIllegalArgumentException( createReader( RemoteThrowable.class ) );
ThrowableTester.INSTANCE.testSerializeCustomException( createWriter( RemoteThrowable.class ) );
ThrowableTester.INSTANCE.testDeserializeCustomException( createReader( RemoteThrowable.class ) );
objectMapper.setSerializationInclusion( Include.NON_NULL );
ThrowableTester.INSTANCE.testSerializeIllegalArgumentExceptionNonNull( createWriter( RemoteThrowable.class ) );
ThrowableTester.INSTANCE.testSerializeCustomExceptionNonNull( createWriter( RemoteThrowable.class ) );
}
public SocketHandler(Socket socket, ConcurrentHashMap<String,MessageReceiver> receivers) throws IOException {
this.reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
this.writer = new PrintWriter(socket.getOutputStream(), true);
this.socket = socket;
this.receivers = receivers;
this.mpr.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); // disable autodetect
this.mpr.setSerializationInclusion(Include.NON_NULL);
this.mpr.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
this.mpr.disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET);
}
@Produces
@GazpachoResource
@RequestScoped
public QuestionnaireResource createQuestionnairResource(HttpServletRequest request) {
RespondentAccount principal = (RespondentAccount) request.getUserPrincipal();
String apiKey = principal.getApiKey();
String secret = principal.getSecret();
logger.info("Getting QuestionnaireResource using api key {}/{} ", apiKey, secret);
JacksonJsonProvider jacksonProvider = new JacksonJsonProvider();
ObjectMapper mapper = new ObjectMapper();
// mapper.findAndRegisterModules();
mapper.registerModule(new JSR310Module());
mapper.setSerializationInclusion(Include.NON_EMPTY);
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
jacksonProvider.setMapper(mapper);
QuestionnaireResource resource = JAXRSClientFactory.create(BASE_URI, QuestionnaireResource.class,
Collections.singletonList(jacksonProvider), null);
// proxies
// WebClient.client(resource).header("Authorization", "GZQ " + apiKey);
Client client = WebClient.client(resource);
ClientConfiguration config = WebClient.getConfig(client);
config.getOutInterceptors().add(new HmacAuthInterceptor(apiKey, secret));
return resource;
}
public DynamoDocumentStoreTemplate(final DatabaseSchemaHolder databaseSchemaHolder) {
super(databaseSchemaHolder);
mapper = new ObjectMapper();
mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.JAVA_LANG_OBJECT);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
mapper.setSerializationInclusion(Include.NON_NULL);
mapper.registerModule(new JodaModule());
}
public static void parseJson(final Swagger swagger, final String filePath) throws IOException {
LOGGER.debug("Spark-Swagger: Start parsing Swagger definitions");
// Create an ObjectMapper mapper for JSON
ObjectMapper mapper = new ObjectMapper(new JsonFactory());
mapper.setSerializationInclusion(Include.NON_NULL);
// Parse endpoints
swagger.parse();
mapper.writeValue(new File(filePath), swagger);
LOGGER.debug("Spark-Swagger: Swagger definitions saved as "+filePath+" [JSON]");
}
private static List<HttpMessageConverter<?>> getMessageConverters(RestTemplate restTemplate) {
// Get existing message converters
List<HttpMessageConverter<?>> messageConverters = restTemplate.getMessageConverters();
messageConverters.clear();
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setSerializationInclusion(Include.NON_NULL);
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
MappingJackson2HttpMessageConverter mycov = new MappingJackson2HttpMessageConverter(objectMapper);
mycov.setPrettyPrint(true);
messageConverters.add(mycov);
return messageConverters;
}
@Test
public void testSerializationOptions_includeNonNullGlobally() throws Exception {
TestObject ref = new TestObject();
ref.setInt1(1);
sut = sut.setSerializationInclusion(Include.NON_NULL);
String serialized = sut.writeValueAsString(JsonView.with(ref));
Map<String, Object> obj = sut.readValue(serialized, NonReplacableKeyMap.class);
assertFalse(obj.containsKey("str1"));
assertEquals(ref.getInt1(), obj.get("int1"));
}
public JacksonContextResolver() {
/*
* Register JodaModule to handle Joda DateTime Objects.
* https://github.com/FasterXML/jackson-datatype-jsr310
*/
mapper.registerModule(new JSR310Module());
mapper.setSerializationInclusion(Include.NON_EMPTY);
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
}
@JsonInclude(Include.NON_NULL)
public RepresentationSkew getRepresentationSkew() {
return representationSkew;
}
@Value.Default
@JsonInclude(Include.NON_EMPTY)
public String host() {
return "";
}
public JsonMapper() {
this(Include.NON_EMPTY);
}
/**
* 创建只输出非Null且非Empty(如List.isEmpty)的属性到Json字符串的Mapper,建议在外部接口中使用.
*/
public static JsonMapper nonEmptyMapper() {
return new JsonMapper(Include.NON_EMPTY);
}
/**
* 创建只输出非Null且非Empty(如List.isEmpty)的属性到Json字符串的Mapper,建议在外部接口中使用.
*/
public static JsonMapper alwaysMapper() {
return new JsonMapper(Include.ALWAYS);
}