类com.fasterxml.jackson.annotation.JsonInclude.Include源码实例Demo

下面列出了怎么用com.fasterxml.jackson.annotation.JsonInclude.Include的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: clouditor   文件: ObjectMapperResolver.java
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());
}
 
源代码4 项目: depends   文件: UnsolvedSymbolDumper.java
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();
	}	
}
 
源代码5 项目: orianna   文件: PipelineConfiguration.java
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());
}
 
源代码7 项目: LDMS   文件: JsonMapper.java
/**
 * 创建只输出初始值被改变的属性到Json字符串的Mapper, 最节约的存储方式,建议在内部接口中使用。
 */
public static JsonMapper nonDefaultMapper() {
	if (jsonMapper == null){
		jsonMapper = new JsonMapper(Include.NON_DEFAULT);
	}
	return jsonMapper;
}
 
源代码8 项目: AIDR   文件: TaskManagerEntityMapper.java
@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;
}
 
源代码9 项目: gwt-jackson   文件: ObjectifyJacksonModuleTest.java
@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 ) );
}
 
源代码10 项目: pulsar   文件: ObjectMapperFactory.java
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;
}
 
源代码11 项目: pulsar   文件: ConfigurationDataUtils.java
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;
}
 
源代码12 项目: heimdall   文件: JsonImpl.java
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;
		}
	}
 
源代码13 项目: gazpachoquest   文件: ClientInterceptorTest.java
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;
}
 
源代码14 项目: j360-dubbo-app-all   文件: JsonMapper.java
public JsonMapper(Include include) {
	mapper = new ObjectMapper();
	// 设置输出时包含属性的风格
	if (include != null) {
		mapper.setSerializationInclusion(include);
	}
	// 设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性
	mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
}
 
源代码15 项目: json-view   文件: JsonViewSerializerTest.java
@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"));
}
 
源代码16 项目: bot-sdk-java   文件: BaseBot.java
/**
 * 根据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);
}
 
源代码17 项目: gwt-jackson   文件: RefStdSerializer.java
@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 ) );
}
 
源代码19 项目: signald   文件: SocketHandler.java
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);
}
 
源代码20 项目: gazpachoquest   文件: ResourceProducer.java
@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;
}
 
源代码21 项目: Cheddar   文件: DynamoDocumentStoreTemplate.java
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());
}
 
源代码22 项目: spark-swagger   文件: SwaggerParser.java
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]");
}
 
源代码23 项目: sdk   文件: AviRestUtils.java
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;
}
 
源代码24 项目: json-view   文件: JsonViewSerializerTest.java
@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"));
}
 
源代码25 项目: gazpachoquest   文件: JacksonContextResolver.java
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);

}
 
源代码26 项目: brooklyn-server   文件: ResourceDto.java
@JsonInclude(Include.NON_NULL)
public RepresentationSkew getRepresentationSkew() {
    return representationSkew;
}
 
源代码27 项目: glowroot   文件: LdapConfig.java
@Value.Default
@JsonInclude(Include.NON_EMPTY)
public String host() {
    return "";
}
 
源代码28 项目: Shop-for-JavaWeb   文件: JsonMapper.java
public JsonMapper() {
	this(Include.NON_EMPTY);
}
 
源代码29 项目: dubai   文件: JsonMapper.java
/**
 * 创建只输出非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);
}
 
 同包方法