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 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 #2
Source File: PipelineConfiguration.java    From orianna with 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 #3
Source File: UnsolvedSymbolDumper.java    From depends with 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 #4
Source File: Jackson2ObjectMapperFactoryBeanTests.java    From spring-analysis-note with 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 #5
Source File: Jackson2ObjectMapperFactoryBeanTests.java    From spring4-understanding with 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 #6
Source File: Jackson2ObjectMapperFactoryBeanTests.java    From java-technology-stack with 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 #7
Source File: BaseBot.java    From bot-sdk-java with 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 #8
Source File: JsonMapper.java    From LDMS with 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 #9
Source File: TaskManagerEntityMapper.java    From AIDR with 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 #10
Source File: ObjectifyJacksonModuleTest.java    From gwt-jackson with 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 #11
Source File: ObjectMapperFactory.java    From pulsar with 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 #12
Source File: JacksonContextResolver.java    From gazpachoquest with 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 #13
Source File: JsonViewSerializerTest.java    From json-view with 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 #14
Source File: ConfigurationDataUtils.java    From pulsar with 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 #15
Source File: JsonImpl.java    From heimdall with 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 #16
Source File: AviRestUtils.java    From sdk with 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 #17
Source File: ClientInterceptorTest.java    From gazpachoquest with 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 #18
Source File: JsonMapper.java    From j360-dubbo-app-all with 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 #19
Source File: DynamoDocumentStoreTemplate.java    From Cheddar with 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 #20
Source File: JsonViewSerializerTest.java    From json-view with 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 #21
Source File: ResourceProducer.java    From gazpachoquest with 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 #22
Source File: SocketHandler.java    From signald with 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 #23
Source File: RemoteLoggingJacksonModuleTest.java    From gwt-jackson with 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 #24
Source File: RefStdSerializer.java    From gwt-jackson with 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 #25
Source File: SwaggerParser.java    From spark-swagger with 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 #26
Source File: FormField.java    From flowable-engine with Apache License 2.0 4 votes vote down vote up
@JsonInclude(Include.NON_EMPTY)
public Map<String, Object> getParams() {
    return params;
}
 
Example #27
Source File: BeanInfoBuilder.java    From gwt-jackson with Apache License 2.0 4 votes vote down vote up
void setInclude( Optional<Include> include ) {
    this.include = include;
}
 
Example #28
Source File: CommitsIndexingMetricProvider.java    From scava with Eclipse Public License 2.0 4 votes vote down vote up
@Override
public void measure(Project project, ProjectDelta delta, Indexing db) {
	
	
	
	loadMetricsDB(project);
	
	if(metricsToIndex.size()>0)
	{
		String projectName = delta.getProject().getName();
		ObjectMapper mapper = new ObjectMapper().setSerializationInclusion(Include.NON_NULL);
		String documentType="commit";
		
		String uid;
		MappingStorage mapping;
		String document;
		String indexName = Indexer.generateIndexName("vcs", documentType, KNOWLEDGE);
		
		VcsProjectDelta vcsd = delta.getVcsDelta();
		for (VcsRepositoryDelta vcsRepositoryDelta : vcsd.getRepoDeltas())
		{	
			VcsRepository repository = vcsRepositoryDelta.getRepository();
			for (VcsCommit commit : vcsRepositoryDelta.getCommits())
			{
				uid = generateUniqueDocumentationId(projectName, repository.getUrl(), commit.getRevision());
				mapping = Mapping.getMapping(documentType);
				
				
				CommitDocument cd = new CommitDocument(projectName,
														uid,
														repository.getUrl(),
														commit);
				enrichCommitDocument(commit, repository.getUrl(), cd);
				try {
					document = mapper.writeValueAsString(cd);
					Indexer.indexDocument(indexName, mapping, documentType, uid, document);
				} catch (JsonProcessingException e) {
					logger.error("Error while processing json:", e);
					e.printStackTrace();
				}
			}
		}
	}
}
 
Example #29
Source File: OneofTest.java    From jackson-datatype-protobuf with Apache License 2.0 4 votes vote down vote up
@Test
public void itWritesOneofWhenSetToDefaultProto3MessageWithAlwaysInclusion() throws IOException {
  String json = camelCase(Include.ALWAYS).writeValueAsString(DEFAULT_PROTO3_MESSAGE);
  JsonNode node = camelCase(Include.ALWAYS).readTree(json).get("proto3Message");
  assertThat(node).isEqualTo(nullProto3Message());
}
 
Example #30
Source File: SyntheticMonitorConfig.java    From glowroot with Apache License 2.0 4 votes vote down vote up
@Value.Default
@JsonInclude(Include.NON_EMPTY)
public String pingUrl() {
    return "";
}