类com.fasterxml.jackson.databind.ser.FilterProvider源码实例Demo

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

/**
 * Filter and optionally wrap the model in {@link MappingJacksonValue} container.
 * @param model the model, as passed on to {@link #renderMergedOutputModel}
 * @param request current HTTP request
 * @return the wrapped or unwrapped value to be rendered
 */
protected Object filterAndWrapModel(Map<String, Object> model, HttpServletRequest request) {
	Object value = filterModel(model);
	Class<?> serializationView = (Class<?>) model.get(JsonView.class.getName());
	FilterProvider filters = (FilterProvider) model.get(FilterProvider.class.getName());
	if (serializationView != null || filters != null) {
		MappingJacksonValue container = new MappingJacksonValue(value);
		if (serializationView != null) {
			container.setSerializationView(serializationView);
		}
		if (filters != null) {
			container.setFilters(filters);
		}
		value = container;
	}
	return value;
}
 
/**
 * Write the actual JSON content to the stream.
 * @param stream the output stream to use
 * @param object the value to be rendered, as returned from {@link #filterModel}
 * @throws IOException if writing failed
 */
protected void writeContent(OutputStream stream, Object object) throws IOException {
	JsonGenerator generator = this.objectMapper.getFactory().createGenerator(stream, this.encoding);
	writePrefix(generator, object);

	Object value = object;
	Class<?> serializationView = null;
	FilterProvider filters = null;

	if (value instanceof MappingJacksonValue) {
		MappingJacksonValue container = (MappingJacksonValue) value;
		value = container.getValue();
		serializationView = container.getSerializationView();
		filters = container.getFilters();
	}

	ObjectWriter objectWriter = (serializationView != null ?
			this.objectMapper.writerWithView(serializationView) : this.objectMapper.writer());
	if (filters != null) {
		objectWriter = objectWriter.with(filters);
	}
	objectWriter.writeValue(generator, value);

	writeSuffix(generator, object);
	generator.flush();
}
 
@Test
public void renderSimpleBeanWithFilters() throws Exception {
	TestSimpleBeanFiltered bean = new TestSimpleBeanFiltered();
	bean.setProperty1("value");
	bean.setProperty2("value");
	Map<String, Object> model = new HashMap<>();
	model.put("bindingResult", mock(BindingResult.class, "binding_result"));
	model.put("foo", bean);
	FilterProvider filters = new SimpleFilterProvider().addFilter("myJacksonFilter",
			SimpleBeanPropertyFilter.serializeAllExcept("property2"));
	model.put(FilterProvider.class.getName(), filters);

	view.setUpdateContentLength(true);
	view.render(model, request, response);

	String content = response.getContentAsString();
	assertTrue(content.length() > 0);
	assertEquals(content.length(), response.getContentLength());
	assertThat(content, containsString("\"property1\":\"value\""));
	assertThat(content, not(containsString("\"property2\":\"value\"")));
	assertFalse(content.contains(FilterProvider.class.getName()));
}
 
/**
 * Filter and optionally wrap the model in {@link MappingJacksonValue} container.
 * @param model the model, as passed on to {@link #renderMergedOutputModel}
 * @param request current HTTP request
 * @return the wrapped or unwrapped value to be rendered
 */
protected Object filterAndWrapModel(Map<String, Object> model, HttpServletRequest request) {
	Object value = filterModel(model);
	Class<?> serializationView = (Class<?>) model.get(JsonView.class.getName());
	FilterProvider filters = (FilterProvider) model.get(FilterProvider.class.getName());
	if (serializationView != null || filters != null) {
		MappingJacksonValue container = new MappingJacksonValue(value);
		if (serializationView != null) {
			container.setSerializationView(serializationView);
		}
		if (filters != null) {
			container.setFilters(filters);
		}
		value = container;
	}
	return value;
}
 
/**
 * Write the actual JSON content to the stream.
 * @param stream the output stream to use
 * @param object the value to be rendered, as returned from {@link #filterModel}
 * @throws IOException if writing failed
 */
protected void writeContent(OutputStream stream, Object object) throws IOException {
	JsonGenerator generator = this.objectMapper.getFactory().createGenerator(stream, this.encoding);
	writePrefix(generator, object);

	Object value = object;
	Class<?> serializationView = null;
	FilterProvider filters = null;

	if (value instanceof MappingJacksonValue) {
		MappingJacksonValue container = (MappingJacksonValue) value;
		value = container.getValue();
		serializationView = container.getSerializationView();
		filters = container.getFilters();
	}

	ObjectWriter objectWriter = (serializationView != null ?
			this.objectMapper.writerWithView(serializationView) : this.objectMapper.writer());
	if (filters != null) {
		objectWriter = objectWriter.with(filters);
	}
	objectWriter.writeValue(generator, value);

	writeSuffix(generator, object);
	generator.flush();
}
 
@Test
public void renderSimpleBeanWithFilters() throws Exception {
	TestSimpleBeanFiltered bean = new TestSimpleBeanFiltered();
	bean.setProperty1("value");
	bean.setProperty2("value");
	Map<String, Object> model = new HashMap<>();
	model.put("bindingResult", mock(BindingResult.class, "binding_result"));
	model.put("foo", bean);
	FilterProvider filters = new SimpleFilterProvider().addFilter("myJacksonFilter",
			SimpleBeanPropertyFilter.serializeAllExcept("property2"));
	model.put(FilterProvider.class.getName(), filters);

	view.setUpdateContentLength(true);
	view.render(model, request, response);

	String content = response.getContentAsString();
	assertTrue(content.length() > 0);
	assertEquals(content.length(), response.getContentLength());
	assertThat(content, containsString("\"property1\":\"value\""));
	assertThat(content, not(containsString("\"property2\":\"value\"")));
	assertFalse(content.contains(FilterProvider.class.getName()));
}
 
@Override
protected ObjectMapper initializeObjectMapper() {
    final ObjectMapper mapper = super.initializeObjectMapper();

    final FilterProvider filters = new SimpleFilterProvider()
            .addFilter("beanObjectFilter", new CasSimpleBeanObjectFilter());
    mapper.setFilters(filters);

    mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    mapper.configure(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS, false);
    mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
    mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    mapper.addMixIn(Object.class, CasSimpleBeanObjectFilter.class);
    mapper.disable(SerializationFeature.INDENT_OUTPUT);
    mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

    return mapper;
}
 
源代码8 项目: tutorials   文件: JsonFilterUnitTest.java
@Test
public void whenSerializingUsingJsonFilter_thenCorrect() throws JsonProcessingException {

    // arrange
    Author author = new Author("Alex", "Theedom");
    FilterProvider filters = new SimpleFilterProvider()
      .addFilter("authorFilter", SimpleBeanPropertyFilter.filterOutAllExcept("lastName"));

    // act
    String result = new ObjectMapper().writer(filters).writeValueAsString(author);

    // assert
    assertThat(from(result).getList("items")).isNull();

    /*
        {
          "lastName": "Theedom"
        }
    */

}
 
@Test
public final void givenTypeHasFilterThatIgnoresFieldByName_whenDtoIsSerialized_thenCorrect() throws JsonParseException, IOException {
    final ObjectMapper mapper = new ObjectMapper();
    final SimpleBeanPropertyFilter theFilter = SimpleBeanPropertyFilter.serializeAllExcept("intValue");
    final FilterProvider filters = new SimpleFilterProvider().addFilter("myFilter", theFilter);

    final MyDtoWithFilter dtoObject = new MyDtoWithFilter();
    dtoObject.setIntValue(12);

    final String dtoAsString = mapper.writer(filters)
        .writeValueAsString(dtoObject);

    assertThat(dtoAsString, not(containsString("intValue")));
    assertThat(dtoAsString, containsString("booleanValue"));
    assertThat(dtoAsString, containsString("stringValue"));
    System.out.println(dtoAsString);
}
 
源代码10 项目: alfresco-remote-api   文件: JsonJacksonTests.java
@Test
public void testSerializeComment() throws IOException
{
    final Comment aComment = new Comment();
    aComment.setContent("<b>There it is</b>");
    ByteArrayOutputStream out = new ByteArrayOutputStream();

    jsonHelper.withWriter(out, new Writer()
    {
        @Override
        public void writeContents(JsonGenerator generator, ObjectMapper objectMapper)
                    throws JsonGenerationException, JsonMappingException, IOException
        {
            FilterProvider fp = new SimpleFilterProvider().addFilter(
                        JacksonHelper.DEFAULT_FILTER_NAME, new ReturnAllBeanProperties());
            objectMapper.writer(fp).writeValue(generator, aComment);
        }
    });
    assertTrue(out.toString().contains("{\"content\":\"<b>There it is</b>\""));
}
 
源代码11 项目: alfresco-remote-api   文件: JsonJacksonTests.java
@Test
public void testNullInComment() throws IOException
{
    final Comment aComment = new Comment();
    aComment.setContent(null);
    ByteArrayOutputStream out = new ByteArrayOutputStream();

    jsonHelper.withWriter(out, new Writer()
    {
        @Override
        public void writeContents(JsonGenerator generator, ObjectMapper objectMapper)
                    throws JsonGenerationException, JsonMappingException, IOException
        {
            FilterProvider fp = new SimpleFilterProvider().addFilter(
                        JacksonHelper.DEFAULT_FILTER_NAME, new ReturnAllBeanProperties());
            objectMapper.writer(fp).writeValue(generator, aComment);
        }
    });
    assertEquals("Null values should not be output.", "{\"canEdit\":false,\"canDelete\":false}",
                out.toString());
}
 
@Test
public void renderSimpleBeanWithFilters() throws Exception {
	TestSimpleBeanFiltered bean = new TestSimpleBeanFiltered();
	bean.setProperty1("value");
	bean.setProperty2("value");
	Map<String, Object> model = new HashMap<String, Object>();
	model.put("bindingResult", mock(BindingResult.class, "binding_result"));
	model.put("foo", bean);
	FilterProvider filters = new SimpleFilterProvider().addFilter("myJacksonFilter",
			SimpleBeanPropertyFilter.serializeAllExcept("property2"));
	model.put(FilterProvider.class.getName(), filters);

	view.setUpdateContentLength(true);
	view.render(model, request, response);

	String content = response.getContentAsString();
	assertTrue(content.length() > 0);
	assertEquals(content.length(), response.getContentLength());
	assertThat(content, containsString("\"property1\":\"value\""));
	assertThat(content, not(containsString("\"property2\":\"value\"")));
	assertFalse(content.contains(FilterProvider.class.getName()));
}
 
源代码13 项目: find   文件: FindConfigFileService.java
protected FindConfigFileService(final FilterProvider filterProvider,
                                final TextEncryptor textEncryptor,
                                final JsonSerializer<FieldPath> fieldPathSerializer,
                                final JsonDeserializer<FieldPath> fieldPathDeserializer) {

    final ObjectMapper objectMapper = new Jackson2ObjectMapperBuilder()
        .featuresToEnable(SerializationFeature.INDENT_OUTPUT)
        .mixIns(customMixins())
        .serializersByType(ImmutableMap.of(FieldPath.class, fieldPathSerializer))
        .deserializersByType(ImmutableMap.of(FieldPath.class, fieldPathDeserializer))
        .createXmlMapper(false)
        .build();

    setConfigFileLocation(CONFIG_FILE_LOCATION);
    setDeprecatedConfigFileLocations(Collections.singletonList(CONFIG_FILE_LOCATION_HP));
    setConfigFileName(CONFIG_FILE_NAME);
    setDefaultConfigFile(getDefaultConfigFile());
    setMapper(objectMapper);
    setTextEncryptor(textEncryptor);
    setFilterProvider(filterProvider);
}
 
源代码14 项目: redisson   文件: ConfigSupport.java
private ObjectMapper createMapper(JsonFactory mapping, ClassLoader classLoader) {
    ObjectMapper mapper = new ObjectMapper(mapping);
    
    mapper.addMixIn(Config.class, ConfigMixIn.class);
    mapper.addMixIn(ReferenceCodecProvider.class, ClassMixIn.class);
    mapper.addMixIn(AddressResolverGroupFactory.class, ClassMixIn.class);
    mapper.addMixIn(Codec.class, ClassMixIn.class);
    mapper.addMixIn(RedissonNodeInitializer.class, ClassMixIn.class);
    mapper.addMixIn(LoadBalancer.class, ClassMixIn.class);
    mapper.addMixIn(NatMapper.class, ClassMixIn.class);
    mapper.addMixIn(NettyHook.class, ClassMixIn.class);
    
    FilterProvider filterProvider = new SimpleFilterProvider()
            .addFilter("classFilter", SimpleBeanPropertyFilter.filterOutAllExcept());
    mapper.setFilterProvider(filterProvider);
    mapper.setSerializationInclusion(Include.NON_NULL);
    mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);

    if (classLoader != null) {
        TypeFactory tf = TypeFactory.defaultInstance()
                .withClassLoader(classLoader);
        mapper.setTypeFactory(tf);
    }
    
    return mapper;
}
 
源代码15 项目: knox   文件: JsonUtils.java
public static String renderAsJsonString(Object obj, FilterProvider filterProvider, DateFormat dateFormat) {
  String json = null;
  ObjectMapper mapper = new ObjectMapper();
  if (filterProvider != null) {
    mapper.setFilterProvider(filterProvider);
  }

  if (dateFormat != null) {
    mapper.setDateFormat(dateFormat);
  }

  try {
    // write JSON to a file
    json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
  } catch ( JsonProcessingException e ) {
    LOG.failedToSerializeObjectToJSON( obj, e );
  }
  return json;
}
 
源代码16 项目: odo   文件: PathController.java
@SuppressWarnings("deprecation")
@RequestMapping(value = "/api/path", method = RequestMethod.GET)
@ResponseBody
public String getPathsForProfile(Model model, String profileIdentifier,
                                 @RequestParam(value = "typeFilter[]", required = false) String[] typeFilter,
                                 @RequestParam(value = "clientUUID", defaultValue = Constants.PROFILE_CLIENT_DEFAULT_ID) String clientUUID) throws Exception {
    int profileId = ControllerUtils.convertProfileIdentifier(profileIdentifier);
    List<EndpointOverride> paths = PathOverrideService.getInstance().getPaths(profileId, clientUUID, typeFilter);

    HashMap<String, Object> jqReturn = Utils.getJQGridJSON(paths, "paths");

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.addMixInAnnotations(Object.class, ViewFilters.GetPathFilter.class);
    String[] ignorableFieldNames = {"possibleEndpoints", "enabledEndpoints"};
    FilterProvider filters = new SimpleFilterProvider().addFilter("Filter properties from the PathController GET",
                                                                  SimpleBeanPropertyFilter.serializeAllExcept(ignorableFieldNames));

    ObjectWriter writer = objectMapper.writer(filters);

    return writer.writeValueAsString(jqReturn);
}
 
源代码17 项目: odo   文件: PathController.java
@RequestMapping(value = "/api/path/test", method = RequestMethod.GET)
@ResponseBody
public String testPath(@RequestParam String url, @RequestParam String profileIdentifier,
                       @RequestParam Integer requestType) throws Exception {
    int profileId = ControllerUtils.convertProfileIdentifier(profileIdentifier);

    List<EndpointOverride> trySelectedRequestPaths = PathOverrideService.getInstance().getSelectedPaths(Constants.OVERRIDE_TYPE_REQUEST,
                                                                                                        ClientService.getInstance().findClient("-1", profileId),
                                                                                                        ProfileService.getInstance().findProfile(profileId), url, requestType, true);

    HashMap<String, Object> jqReturn = Utils.getJQGridJSON(trySelectedRequestPaths, "paths");

    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.addMixInAnnotations(Object.class, ViewFilters.GetPathFilter.class);
    String[] ignorableFieldNames = {"possibleEndpoints", "enabledEndpoints"};
    FilterProvider filters = new SimpleFilterProvider().addFilter("Filter properties from the PathController GET",
                                                                  SimpleBeanPropertyFilter.serializeAllExcept(ignorableFieldNames));

    ObjectWriter writer = objectMapper.writer(filters);

    return writer.writeValueAsString(jqReturn);
}
 
源代码18 项目: tutorials   文件: IgnoreFieldsWithFilterUnitTest.java
@Test
public final void givenTypeHasFilterThatIgnoresFieldByName_whenDtoIsSerialized_thenCorrect() throws JsonParseException, IOException {
    final ObjectMapper mapper = new ObjectMapper();
    final SimpleBeanPropertyFilter theFilter = SimpleBeanPropertyFilter.serializeAllExcept("intValue");
    final FilterProvider filters = new SimpleFilterProvider().addFilter("myFilter", theFilter);

    final MyDtoWithFilter dtoObject = new MyDtoWithFilter();
    dtoObject.setIntValue(12);

    final String dtoAsString = mapper.writer(filters)
        .writeValueAsString(dtoObject);

    assertThat(dtoAsString, not(containsString("intValue")));
    assertThat(dtoAsString, containsString("booleanValue"));
    assertThat(dtoAsString, containsString("stringValue"));
    System.out.println(dtoAsString);
}
 
/**
 * Filter out undesired attributes from the given model.
 * The return value can be either another {@link Map} or a single value object.
 * <p>The default implementation removes {@link BindingResult} instances and entries
 * not included in the {@link #setModelKeys modelKeys} property.
 * @param model the model, as passed on to {@link #renderMergedOutputModel}
 * @return the value to be rendered
 */
@Override
protected Object filterModel(Map<String, Object> model) {
	Map<String, Object> result = new HashMap<>(model.size());
	Set<String> modelKeys = (!CollectionUtils.isEmpty(this.modelKeys) ? this.modelKeys : model.keySet());
	model.forEach((clazz, value) -> {
		if (!(value instanceof BindingResult) && modelKeys.contains(clazz) &&
				!clazz.equals(JsonView.class.getName()) &&
				!clazz.equals(FilterProvider.class.getName())) {
			result.put(clazz, value);
		}
	});
	return (this.extractValueFromSingleKeyModel && result.size() == 1 ? result.values().iterator().next() : result);
}
 
/**
 * Filter out undesired attributes from the given model.
 * The return value can be either another {@link Map} or a single value object.
 * <p>The default implementation removes {@link BindingResult} instances and entries
 * not included in the {@link #setModelKeys modelKeys} property.
 * @param model the model, as passed on to {@link #renderMergedOutputModel}
 * @return the value to be rendered
 */
@Override
protected Object filterModel(Map<String, Object> model) {
	Map<String, Object> result = new HashMap<>(model.size());
	Set<String> modelKeys = (!CollectionUtils.isEmpty(this.modelKeys) ? this.modelKeys : model.keySet());
	model.forEach((clazz, value) -> {
		if (!(value instanceof BindingResult) && modelKeys.contains(clazz) &&
				!clazz.equals(JsonView.class.getName()) &&
				!clazz.equals(FilterProvider.class.getName())) {
			result.put(clazz, value);
		}
	});
	return (this.extractValueFromSingleKeyModel && result.size() == 1 ? result.values().iterator().next() : result);
}
 
public JsonNode handleProperty(IAPI desired, IAPI actual, JsonNode response) {
	String[] propertiesToExclude = {"certFile", "useForInbound", "useForOutbound"};
	FilterProvider filters = new SimpleFilterProvider()  
		      .addFilter("IgnoreImportFields",   
		          SimpleBeanPropertyFilter.serializeAllExcept(propertiesToExclude) );
	ObjectMapper objectMapper = new ObjectMapper();
	objectMapper.setFilterProvider(filters);
	if(desired.getCaCerts().size()!=0) {
		((ObjectNode)response).replace("caCerts", objectMapper.valueToTree(desired.getCaCerts()));
	}
	return response;
}
 
源代码22 项目: heimdall   文件: Trace.java
private ObjectMapper mapper() {
    SimpleBeanPropertyFilter customFilter;

    if (!this.printFilters) {
        customFilter = SimpleBeanPropertyFilter.serializeAllExcept("filters");
    } else {
        customFilter = SimpleBeanPropertyFilter.serializeAll();
    }

    FilterProvider filters = new SimpleFilterProvider().addFilter("customFilter", customFilter);

    return new ObjectMapper().setFilterProvider(filters);

}
 
源代码23 项目: lams   文件: MappingJackson2JsonView.java
/**
 * Filter out undesired attributes from the given model.
 * The return value can be either another {@link Map} or a single value object.
 * <p>The default implementation removes {@link BindingResult} instances and entries
 * not included in the {@link #setModelKeys renderedAttributes} property.
 * @param model the model, as passed on to {@link #renderMergedOutputModel}
 * @return the value to be rendered
 */
@Override
protected Object filterModel(Map<String, Object> model) {
	Map<String, Object> result = new HashMap<String, Object>(model.size());
	Set<String> modelKeys = (!CollectionUtils.isEmpty(this.modelKeys) ? this.modelKeys : model.keySet());
	for (Map.Entry<String, Object> entry : model.entrySet()) {
		if (!(entry.getValue() instanceof BindingResult) && modelKeys.contains(entry.getKey()) &&
				!entry.getKey().equals(JsonView.class.getName()) &&
				!entry.getKey().equals(FilterProvider.class.getName())) {
			result.put(entry.getKey(), entry.getValue());
		}
	}
	return (this.extractValueFromSingleKeyModel && result.size() == 1 ? result.values().iterator().next() : result);
}
 
源代码24 项目: lams   文件: AbstractJackson2View.java
/**
 * Filter and optionally wrap the model in {@link MappingJacksonValue} container.
 * @param model the model, as passed on to {@link #renderMergedOutputModel}
 * @param request current HTTP request
 * @return the wrapped or unwrapped value to be rendered
 */
protected Object filterAndWrapModel(Map<String, Object> model, HttpServletRequest request) {
	Object value = filterModel(model);
	Class<?> serializationView = (Class<?>) model.get(JsonView.class.getName());
	FilterProvider filters = (FilterProvider) model.get(FilterProvider.class.getName());
	if (serializationView != null || filters != null) {
		MappingJacksonValue container = new MappingJacksonValue(value);
		container.setSerializationView(serializationView);
		container.setFilters(filters);
		value = container;
	}
	return value;
}
 
源代码25 项目: lams   文件: AbstractJackson2View.java
/**
 * Write the actual JSON content to the stream.
 * @param stream the output stream to use
 * @param object the value to be rendered, as returned from {@link #filterModel}
 * @throws IOException if writing failed
 */
protected void writeContent(OutputStream stream, Object object) throws IOException {
	JsonGenerator generator = this.objectMapper.getFactory().createGenerator(stream, this.encoding);

	writePrefix(generator, object);
	Class<?> serializationView = null;
	FilterProvider filters = null;
	Object value = object;

	if (value instanceof MappingJacksonValue) {
		MappingJacksonValue container = (MappingJacksonValue) value;
		value = container.getValue();
		serializationView = container.getSerializationView();
		filters = container.getFilters();
	}
	if (serializationView != null) {
		this.objectMapper.writerWithView(serializationView).writeValue(generator, value);
	}
	else if (filters != null) {
		this.objectMapper.writer(filters).writeValue(generator, value);
	}
	else {
		this.objectMapper.writeValue(generator, value);
	}
	writeSuffix(generator, object);
	generator.flush();
}
 
源代码26 项目: lams   文件: StdSerializer.java
/**
 * Helper method used to locate filter that is needed, based on filter id
 * this serializer was constructed with.
 * 
 * @since 2.3
 */
protected PropertyFilter findPropertyFilter(SerializerProvider provider,
        Object filterId, Object valueToFilter)
    throws JsonMappingException
{
    FilterProvider filters = provider.getFilterProvider();
    // Not ok to miss the provider, if a filter is declared to be needed.
    if (filters == null) {
        provider.reportBadDefinition(handledType(),
                "Cannot resolve PropertyFilter with id '"+filterId+"'; no FilterProvider configured");
    }
    // But whether unknown ids are ok just depends on filter provider; if we get null that's fine
    return filters.findPropertyFilter(filterId, valueToFilter);
}
 
源代码27 项目: lams   文件: SerializationConfig.java
private SerializationConfig(SerializationConfig src, FilterProvider filters)
{
    super(src);
    _serFeatures = src._serFeatures;
    _filterProvider = filters;
    _defaultPrettyPrinter = src._defaultPrettyPrinter;
    _generatorFeatures = src._generatorFeatures;
    _generatorFeaturesToChange = src._generatorFeaturesToChange;
    _formatWriteFeatures = src._formatWriteFeatures;
    _formatWriteFeaturesToChange = src._formatWriteFeaturesToChange;
}
 
源代码28 项目: alfresco-remote-api   文件: JsonJacksonTests.java
@Test
public void testSerializeMultipleObjects() throws IOException
{
    final Collection<Comment> allComments = new ArrayList<Comment>();
    Comment aComment = new Comment();
    aComment.setContent("<b>There it is</b>");
    allComments.add(aComment);
    aComment = new Comment();
    aComment.setContent("<p>I agree with the author</p>");
    allComments.add(aComment);

    ByteArrayOutputStream out = new ByteArrayOutputStream();

    jsonHelper.withWriter(out, new Writer()
    {
        @Override
        public void writeContents(JsonGenerator generator, ObjectMapper objectMapper)
                    throws JsonGenerationException, JsonMappingException, IOException
        {
            FilterProvider fp = new SimpleFilterProvider().addFilter(
                        JacksonHelper.DEFAULT_FILTER_NAME, new ReturnAllBeanProperties());
            objectMapper.writer(fp).writeValue(generator, allComments);
        }
    });
    assertTrue(out.toString().contains("content\":\"<b>There it is</b>"));
    assertTrue(out.toString().contains("content\":\"<p>I agree with the author</p>"));
}
 
源代码29 项目: cerebro   文件: CerebroController.java
@ExceptionHandler(CerebroException.class)
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
public String getErrorCode(final CerebroException exception) throws IOException {
    LOGGER.error("Service error", exception);
    ObjectMapper objectMapper = new ObjectMapper();
    FilterProvider filterProvider = new SimpleFilterProvider().addFilter("responseFilter",
        SimpleBeanPropertyFilter.filterOutAllExcept("errorCode", "errorMessage"));
    objectMapper.setFilterProvider(filterProvider);
    return objectMapper.writeValueAsString(exception);
}
 
/**
 * Filter out undesired attributes from the given model.
 * The return value can be either another {@link Map} or a single value object.
 * <p>The default implementation removes {@link BindingResult} instances and entries
 * not included in the {@link #setModelKeys renderedAttributes} property.
 * @param model the model, as passed on to {@link #renderMergedOutputModel}
 * @return the value to be rendered
 */
@Override
protected Object filterModel(Map<String, Object> model) {
	Map<String, Object> result = new HashMap<String, Object>(model.size());
	Set<String> modelKeys = (!CollectionUtils.isEmpty(this.modelKeys) ? this.modelKeys : model.keySet());
	for (Map.Entry<String, Object> entry : model.entrySet()) {
		if (!(entry.getValue() instanceof BindingResult) && modelKeys.contains(entry.getKey()) &&
				!entry.getKey().equals(JsonView.class.getName()) &&
				!entry.getKey().equals(FilterProvider.class.getName())) {
			result.put(entry.getKey(), entry.getValue());
		}
	}
	return (this.extractValueFromSingleKeyModel && result.size() == 1 ? result.values().iterator().next() : result);
}
 
 类方法
 同包方法