com.fasterxml.jackson.annotation.JsonInclude.Include Java Examples

The following examples show how to use com.fasterxml.jackson.annotation.JsonInclude.Include. 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 Project: clouditor   Author: clouditor   File: ObjectMapperResolver.java    License: 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 #2
Source Project: spring-analysis-note   Author: Vip-Augus   File: Jackson2ObjectMapperFactoryBeanTests.java    License: MIT License 6 votes vote down vote up
@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());
}
 
Example #3
Source Project: java-technology-stack   Author: codeEngraver   File: Jackson2ObjectMapperFactoryBeanTests.java    License: MIT License 6 votes vote down vote up
@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());
}
 
Example #4
Source Project: depends   Author: multilang-depends   File: UnsolvedSymbolDumper.java    License: MIT License 6 votes vote down vote up
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();
	}	
}
 
Example #5
Source Project: orianna   Author: meraki-analytics   File: PipelineConfiguration.java    License: MIT License 6 votes vote down vote up
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;
}
 
Example #6
Source Project: spring4-understanding   Author: langtianya   File: Jackson2ObjectMapperFactoryBeanTests.java    License: Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #7
Source Project: LDMS   Author: iCodingStar   File: JsonMapper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 创建只输出初始值被改变的属性到Json字符串的Mapper, 最节约的存储方式,建议在内部接口中使用。
 */
public static JsonMapper nonDefaultMapper() {
	if (jsonMapper == null){
		jsonMapper = new JsonMapper(Include.NON_DEFAULT);
	}
	return jsonMapper;
}
 
Example #8
Source Project: AIDR   Author: qcri-social   File: TaskManagerEntityMapper.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
@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;
}
 
Example #9
Source Project: gwt-jackson   Author: nmorel   File: ObjectifyJacksonModuleTest.java    License: Apache License 2.0 5 votes vote down vote up
@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 ) );
}
 
Example #10
Source Project: pulsar   Author: apache   File: ObjectMapperFactory.java    License: Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #11
Source Project: pulsar   Author: apache   File: ConfigurationDataUtils.java    License: Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #12
Source Project: heimdall   Author: getheimdall   File: JsonImpl.java    License: Apache License 2.0 5 votes vote down vote up
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;
		}
	}
 
Example #13
Source Project: gazpachoquest   Author: antoniomaria   File: ClientInterceptorTest.java    License: GNU General Public License v3.0 5 votes vote down vote up
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;
}
 
Example #14
Source Project: j360-dubbo-app-all   Author: xuminwlt   File: JsonMapper.java    License: Apache License 2.0 5 votes vote down vote up
public JsonMapper(Include include) {
	mapper = new ObjectMapper();
	// 设置输出时包含属性的风格
	if (include != null) {
		mapper.setSerializationInclusion(include);
	}
	// 设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性
	mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
}
 
Example #15
Source Project: json-view   Author: monitorjbl   File: JsonViewSerializerTest.java    License: GNU General Public License v3.0 5 votes vote down vote up
@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"));
}
 
Example #16
Source Project: bot-sdk-java   Author: dueros   File: BaseBot.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 根据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);
}
 
Example #17
Source Project: gwt-jackson   Author: nmorel   File: RefStdSerializer.java    License: Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example #18
Source Project: gwt-jackson   Author: nmorel   File: RemoteLoggingJacksonModuleTest.java    License: Apache License 2.0 5 votes vote down vote up
@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 ) );
}
 
Example #19
Source Project: signald   Author: thefinn93   File: SocketHandler.java    License: GNU General Public License v3.0 5 votes vote down vote up
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);
}
 
Example #20
Source Project: gazpachoquest   Author: antoniomaria   File: ResourceProducer.java    License: GNU General Public License v3.0 5 votes vote down vote up
@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;
}
 
Example #21
Source Project: Cheddar   Author: travel-cloud   File: DynamoDocumentStoreTemplate.java    License: Apache License 2.0 5 votes vote down vote up
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());
}
 
Example #22
Source Project: spark-swagger   Author: manusant   File: SwaggerParser.java    License: Apache License 2.0 5 votes vote down vote up
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]");
}
 
Example #23
Source Project: sdk   Author: avinetworks   File: AviRestUtils.java    License: Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #24
Source Project: json-view   Author: monitorjbl   File: JsonViewSerializerTest.java    License: GNU General Public License v3.0 5 votes vote down vote up
@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"));
}
 
Example #25
Source Project: gazpachoquest   Author: antoniomaria   File: JacksonContextResolver.java    License: GNU General Public License v3.0 5 votes vote down vote up
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);

}
 
Example #26
Source Project: brooklyn-server   Author: apache   File: ResourceDto.java    License: Apache License 2.0 4 votes vote down vote up
@JsonInclude(Include.NON_NULL)
public RepresentationSkew getRepresentationSkew() {
    return representationSkew;
}
 
Example #27
Source Project: glowroot   Author: glowroot   File: LdapConfig.java    License: Apache License 2.0 4 votes vote down vote up
@Value.Default
@JsonInclude(Include.NON_EMPTY)
public String host() {
    return "";
}
 
Example #28
Source Project: Shop-for-JavaWeb   Author: EleTeam   File: JsonMapper.java    License: MIT License 4 votes vote down vote up
public JsonMapper() {
	this(Include.NON_EMPTY);
}
 
Example #29
Source Project: dubai   Author: guuuuo   File: JsonMapper.java    License: MIT License 4 votes vote down vote up
/**
 * 创建只输出非Null且非Empty(如List.isEmpty)的属性到Json字符串的Mapper,建议在外部接口中使用.
 */
public static JsonMapper nonEmptyMapper() {
	return new JsonMapper(Include.NON_EMPTY);
}
 
Example #30
Source Project: springcloud-idempotent-starter   Author: amu007   File: JsonMapper.java    License: GNU General Public License v3.0 4 votes vote down vote up
/**
 * 创建只输出非Null且非Empty(如List.isEmpty)的属性到Json字符串的Mapper,建议在外部接口中使用.
 */
public static JsonMapper alwaysMapper() {
	return new JsonMapper(Include.ALWAYS);
}