com.fasterxml.jackson.databind.module.SimpleModule Java Examples

The following examples show how to use com.fasterxml.jackson.databind.module.SimpleModule. 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: WebConfig.java    From wetech-admin with MIT License 6 votes vote down vote up
@Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
        ObjectMapper objectMapper = jackson2HttpMessageConverter.getObjectMapper();

        //不显示为null的字段
//        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        //序列化枚举是以ordinal()来输出
//        objectMapper.configure(SerializationFeature.WRITE_ENUMS_USING_INDEX, true);
        SimpleModule simpleModule = new SimpleModule();
//        simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
//        simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
        objectMapper.registerModule(simpleModule);

        jackson2HttpMessageConverter.setObjectMapper(objectMapper);
        //放到第一个
        converters.add(0, jackson2HttpMessageConverter);
    }
 
Example #2
Source File: JacksonConfigParserTest.java    From java-sdk with Apache License 2.0 6 votes vote down vote up
@Test
public void parseInvalidAudience() throws Exception {
    thrown.expect(InvalidAudienceCondition.class);
    String audienceString =
        "{" +
            "\"id\": \"123\"," +
            "\"name\":\"blah\"," +
            "\"conditions\":" +
            "\"[\\\"and\\\", [\\\"or\\\", [\\\"or\\\", \\\"123\\\"]]]\"" +
            "}";

    ObjectMapper objectMapper = new ObjectMapper();
    SimpleModule module = new SimpleModule();
    module.addDeserializer(Audience.class, new AudienceJacksonDeserializer(objectMapper));
    module.addDeserializer(Condition.class, new ConditionJacksonDeserializer(objectMapper));
    objectMapper.registerModule(module);

    Audience audience = objectMapper.readValue(audienceString, Audience.class);
    assertNotNull(audience);
    assertNotNull(audience.getConditions());
}
 
Example #3
Source File: AdditionalPropertiesSerializer.java    From botbuilder-java with MIT License 6 votes vote down vote up
/**
 * Gets a module wrapping this serializer as an adapter for the Jackson
 * ObjectMapper.
 *
 * @param mapper the object mapper for default serializations
 * @return a simple module to be plugged onto Jackson ObjectMapper.
 */
public static SimpleModule getModule(final ObjectMapper mapper) {
    SimpleModule module = new SimpleModule();
    module.setSerializerModifier(new BeanSerializerModifier() {
        @Override
        public JsonSerializer<?> modifySerializer(SerializationConfig config, BeanDescription beanDesc, JsonSerializer<?> serializer) {
            for (Class<?> c : TypeToken.of(beanDesc.getBeanClass()).getTypes().classes().rawTypes()) {
                if (c.isAssignableFrom(Object.class)) {
                    continue;
                }
                Field[] fields = c.getDeclaredFields();
                for (Field field : fields) {
                    if ("additionalProperties".equalsIgnoreCase(field.getName())) {
                        JsonProperty property = field.getAnnotation(JsonProperty.class);
                        if (property != null && property.value().isEmpty()) {
                            return new AdditionalPropertiesSerializer(beanDesc.getBeanClass(), serializer, mapper);
                        }
                    }
                }
            }
            return serializer;
        }
    });
    return module;
}
 
Example #4
Source File: ObjectMappers.java    From buck with Apache License 2.0 6 votes vote down vote up
private static ObjectMapper addCustomModules(ObjectMapper mapper, boolean intern) {
  // with this mixin UnconfiguredTargetNode properties are flattened with
  // UnconfiguredTargetNodeWithDeps
  // properties
  // for prettier view. It only works for non-typed serialization.
  mapper.addMixIn(
      UnconfiguredTargetNodeWithDeps.class,
      UnconfiguredTargetNodeWithDeps.UnconfiguredTargetNodeWithDepsUnwrappedMixin.class);

  // Serialize and deserialize UnconfiguredBuildTarget as string
  SimpleModule buildTargetModule = new SimpleModule("BuildTarget");
  buildTargetModule.addSerializer(UnconfiguredBuildTarget.class, new ToStringSerializer());
  buildTargetModule.addDeserializer(
      UnconfiguredBuildTarget.class,
      new FromStringDeserializer<UnconfiguredBuildTarget>(UnconfiguredBuildTarget.class) {
        @Override
        protected UnconfiguredBuildTarget _deserialize(
            String value, DeserializationContext ctxt) {
          return UnconfiguredBuildTargetParser.parse(value, intern);
        }
      });
  mapper.registerModule(buildTargetModule);
  mapper.registerModule(forwardRelativePathModule());
  return mapper;
}
 
Example #5
Source File: JsonSdlObjectMapper.java    From cm_ext with Apache License 2.0 6 votes vote down vote up
/**
 * We construct a new jackson object mapper for the parser since we want to
 * add some configuration that we don't want to apply to our global object
 * mapper. This object mapper has the following features:
 *
 * 1. Does not fail if there is an unknown element in the json file, by default.
 * It simply ignores the element and continues reading. This can be reconfigured.
 *
 * 2. We use Mr. Bean for bean materialization during deserialization. Mr Bean
 * uses ASM to create classes at runtime that conform to your abstract class
 * or interface. This allows us to define an immutable interface for the
 * service descriptor and not have to write out all the concrete classes.
 *
 * 3. We add mixin classes to the object mapper to let jackson know of
 * property name remaps.
 * @return
 */
private ObjectMapper createObjectMapper() {
  final Map<Class<?>, Class<?>> mixins = new HashMap<Class<?>, Class<?>>() {{
    put(Parameter.class, ParameterMixin.class);
    put(ConfigGenerator.class, GeneratorMixin.class);
    put(DependencyExtension.class, DependencyExtensionMixin.class);
    put(PlacementRuleDescriptor.class, PlacementRuleMixin.class);
    put(SslServerDescriptor.class, SslServerDescriptorTypeMixin.class);
    put(SslClientDescriptor.class, SslClientDescriptorTypeMixin.class);
  }};

  ObjectMapper m = new ObjectMapper();
  m.registerModule(new SimpleModule() {
    @Override
    public void setupModule(SetupContext context) {
      for (Entry<Class<?>, Class<?>> entry : mixins.entrySet()) {
        context.setMixInAnnotations(entry.getKey(), entry.getValue());
      }
    }
  });
  m.registerModule(new MrBeanModule());
  m.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,
          false);
  m.configure(Feature.ALLOW_COMMENTS, true);
  return m;
}
 
Example #6
Source File: JacksonIssue429Test.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testStackTraceElementWithCustom() throws Exception {
    // first, via bean that contains StackTraceElement
    final StackTraceBean bean = MAPPER.readValue(aposToQuotes("{'Location':'foobar'}"), StackTraceBean.class);
    Assert.assertNotNull(bean);
    Assert.assertNotNull(bean.location);
    Assert.assertEquals(StackTraceBean.NUM, bean.location.getLineNumber());

    // and then directly, iff registered
    final ObjectMapper mapper = new ObjectMapper();
    final SimpleModule module = new SimpleModule();
    module.addDeserializer(StackTraceElement.class, new Jackson429StackTraceElementDeserializer());
    mapper.registerModule(module);

    final StackTraceElement elem = mapper.readValue(
            aposToQuotes("{'class':'package.SomeClass','method':'someMethod','file':'SomeClass.java','line':123}"),
            StackTraceElement.class);
    Assert.assertNotNull(elem);
    Assert.assertEquals(StackTraceBean.NUM, elem.getLineNumber());
}
 
Example #7
Source File: MarshallerService.java    From dawnsci with Eclipse Public License 1.0 6 votes vote down vote up
private final ObjectMapper createOldMapper() {

		ObjectMapper mapper = new ObjectMapper();

		// Use custom serialization for IPosition objects
		// (Otherwise all IPosition subclasses will need to become simple beans, i.e. no-arg constructors with getters
		// and setters for all fields. MapPosition.getNames() caused problems because it just returns keys from the map
		// and has no corresponding setter.)
		SimpleModule module = new SimpleModule();
		try { // Extension points might still work
			createModuleExtensions(module);
		} catch (Exception ne) {
			// Ignored, we allow the non-osgi mapper to continue without extension points.
		}
		mapper.registerModule(module);

		// Be careful adjusting these settings - changing them will probably cause various unit tests to fail which
		// check the exact contents of the serialized JSON string
		mapper.setSerializationInclusion(Include.NON_NULL);
		//mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
		return mapper;
	}
 
Example #8
Source File: GridMetadataContainer.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * JSON serializer for this object
 *
 * @return the network serialized
 * @throws SerializationException
 */
@JsonIgnore
public String toJSONString() throws it.eng.spagobi.commons.serializer.SerializationException {
	ObjectMapper mapper = new ObjectMapper();
	String s = "";
	try {
		SimpleModule simpleModule = new SimpleModule("SimpleModule", new Version(1, 0, 0, null));
		simpleModule.addSerializer(GridMetadataContainer.class, new GridMetadataContainerJSONSerializer());
		mapper.registerModule(simpleModule);
		s = mapper.writeValueAsString(this);
	} catch (Exception e) {
		throw new SpagoBIRuntimeException("Error while transforming into a JSON object", e);
	}
	// s = StringEscapeUtils.unescapeJavaScript(s);
	return s;
}
 
Example #9
Source File: ElasticsearchIO.java    From beam with Apache License 2.0 6 votes vote down vote up
@Setup
public void setup() throws IOException {
  ConnectionConfiguration connectionConfiguration = spec.getConnectionConfiguration();
  backendVersion = getBackendVersion(connectionConfiguration);
  restClient = connectionConfiguration.createClient();

  retryBackoff =
      FluentBackoff.DEFAULT.withMaxRetries(0).withInitialBackoff(RETRY_INITIAL_BACKOFF);

  if (spec.getRetryConfiguration() != null) {
    retryBackoff =
        FluentBackoff.DEFAULT
            .withInitialBackoff(RETRY_INITIAL_BACKOFF)
            .withMaxRetries(spec.getRetryConfiguration().getMaxAttempts() - 1)
            .withMaxCumulativeBackoff(spec.getRetryConfiguration().getMaxDuration());
  }
  // configure a custom serializer for metadata to be able to change serialization based
  // on ES version
  SimpleModule module = new SimpleModule();
  module.addSerializer(DocumentMetadata.class, new DocumentMetadataSerializer());
  OBJECT_MAPPER.registerModule(module);
}
 
Example #10
Source File: EntityFormatter.java    From FROST-Server with GNU Lesser General Public License v3.0 6 votes vote down vote up
private static ObjectMapper createObjectMapper() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
    mapper.setPropertyNamingStrategy(new EntitySetCamelCaseNamingStrategy());

    MixinUtils.addMixins(mapper);

    SimpleModule module = new SimpleModule();
    GeoJsonSerializer geoJsonSerializer = new GeoJsonSerializer();
    for (String encodingType : GeoJsonDeserializier.ENCODINGS) {
        CustomSerializationManager.getInstance().registerSerializer(encodingType, geoJsonSerializer);
    }

    module.addSerializer(Entity.class, new EntitySerializer());
    module.addSerializer(EntitySetResult.class, new EntitySetResultSerializer());
    module.addSerializer(TimeValue.class, new TimeValueSerializer());
    mapper.registerModule(module);
    return mapper;
}
 
Example #11
Source File: ObjectMapperFactory.java    From client-sdk-java with Apache License 2.0 6 votes vote down vote up
private static ObjectMapper configureObjectMapper(
        ObjectMapper objectMapper, boolean shouldIncludeRawResponses) {
    if (shouldIncludeRawResponses) {
        SimpleModule module = new SimpleModule();
        module.setDeserializerModifier(new BeanDeserializerModifier() {
            @Override
            public JsonDeserializer<?> modifyDeserializer(DeserializationConfig config,
                                                          BeanDescription beanDesc,
                                                          JsonDeserializer<?> deserializer) {
                if (Response.class.isAssignableFrom(beanDesc.getBeanClass())) {
                    return new RawResponseDeserializer(deserializer);
                }

                return deserializer;
            }
        });

        objectMapper.registerModule(module);
    }

    objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    return objectMapper;
}
 
Example #12
Source File: VertxRestService.java    From atomix with Apache License 2.0 6 votes vote down vote up
protected ObjectMapper createObjectMapper() {
  ObjectMapper mapper = new ObjectMapper();

  mapper.setPropertyNamingStrategy(new ConfigPropertyNamingStrategy());
  mapper.enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS);
  mapper.enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES);
  mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
  mapper.configure(JsonParser.Feature.ALLOW_YAML_COMMENTS, true);

  SimpleModule module = new SimpleModule("PolymorphicTypes");
  module.addDeserializer(PartitionGroupConfig.class, new PartitionGroupDeserializer(atomix.getRegistry()));
  module.addDeserializer(PrimitiveProtocolConfig.class, new PrimitiveProtocolDeserializer(atomix.getRegistry()));
  module.addDeserializer(PrimitiveConfig.class, new PrimitiveConfigDeserializer(atomix.getRegistry()));
  mapper.registerModule(module);

  return mapper;
}
 
Example #13
Source File: AbstractStoresTest.java    From alfresco-simple-content-stores with Apache License 2.0 6 votes vote down vote up
/**
 * Configures and constructs a Resteasy client to use for calling the Alfresco Public ReST API in the dockerised deployment.
 *
 * @return the configured client
 */
protected static ResteasyClient setupResteasyClient()
{
    final SimpleModule module = new SimpleModule();
    module.setDeserializerModifier(new RestAPIBeanDeserializerModifier());

    final ResteasyJackson2Provider resteasyJacksonProvider = new ResteasyJackson2Provider();
    final ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(Include.NON_EMPTY);
    mapper.registerModule(module);
    resteasyJacksonProvider.setMapper(mapper);

    final LocalResteasyProviderFactory resteasyProviderFactory = new LocalResteasyProviderFactory(new ResteasyProviderFactoryImpl());
    resteasyProviderFactory.register(resteasyJacksonProvider);
    // will cause a warning regarding Jackson provider which is already registered
    RegisterBuiltin.register(resteasyProviderFactory);
    resteasyProviderFactory.register(new MultiValuedParamConverterProvider());

    final ResteasyClient client = new ResteasyClientBuilderImpl().providerFactory(resteasyProviderFactory).build();
    return client;
}
 
Example #14
Source File: RestObjectMapper.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
public RestObjectMapper() {
  getFactory().disable(Feature.AUTO_CLOSE_SOURCE);
  // Enable features that can tolerance errors and not enable those make more constraints for compatible reasons.
  // Developers can use validation api to do more checks.
  disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
  disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
  // no view annotations shouldn't be included in JSON
  disable(MapperFeature.DEFAULT_VIEW_INCLUSION);
  disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
  enable(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS);
  enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);

  SimpleModule module = new SimpleModule();
  // custom types
  module.addSerializer(JsonObject.class, new JsonObjectSerializer());
  registerModule(module);
  registerModule(new JavaTimeModule());
}
 
Example #15
Source File: JacksonRepoTest.java    From immutables with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
  final MongoDatabase database = context.database();
  this.collection = database.getCollection("jackson").withDocumentClass(BsonDocument.class);

  SimpleModule module = new SimpleModule(); // for our local serializers of Date and ObjectId
  module.addDeserializer(Date.class, new DateDeserializer());
  module.addSerializer(new DateSerializer());
  module.addDeserializer(ObjectId.class, new ObjectIdDeserializer());
  module.addSerializer(new ObjectIdSerializer());
  module.addDeserializer(UUID.class, new UUIDDeserializer(UuidRepresentation.JAVA_LEGACY));

  ObjectMapper mapper = new ObjectMapper()
      // to support bson types like: Document, BsonValue etc.
      .registerModule(JacksonCodecs.module(MongoClient.getDefaultCodecRegistry()))
      .registerModule(new GuavaModule())
      .registerModule(module);

  RepositorySetup setup = RepositorySetup.builder()
          .database(database)
          .codecRegistry(JacksonCodecs.registryFromMapper(mapper))
          .executor(MoreExecutors.newDirectExecutorService())
          .build();

  this.repository = new JacksonRepository(setup);
}
 
Example #16
Source File: RestClientConfig.java    From elastic-rest-spring-wrapper with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Autowired
public void configObjectMapper(ObjectMapper objectMapper) {
    AggregationDeserializer deserializer = new AggregationDeserializer();
    deserializer.register("sterms", TermsAggregation.class);
    deserializer.register("histogram", HistogramAggregation.class);
    deserializer.register("date_histogram", DateHistogramAggregation.class);
    deserializer.register("avg", SingleValueMetricsAggregation.class);
    deserializer.register("sum", SingleValueMetricsAggregation.class);
    deserializer.register("max", SingleValueMetricsAggregation.class);
    deserializer.register("min", SingleValueMetricsAggregation.class);
    deserializer.register("cardinality", SingleValueMetricsAggregation.class);
    deserializer.register("value_count", SingleValueMetricsAggregation.class);

    SimpleModule module = new SimpleModule("AggregationDeserializer",
            new Version(1, 0, 0, null, "eu.luminis.elastic", "aggregation-elastic"));
    module.addDeserializer(Aggregation.class, deserializer);
    module.addKeyDeserializer(String.class, new AggregationKeyDeserializer());

    objectMapper.registerModule(module);
}
 
Example #17
Source File: ParseCEF.java    From nifi with Apache License 2.0 6 votes vote down vote up
@OnScheduled
public void OnScheduled(final ProcessContext context) {

    // Configure jackson mapper before spawning onTriggers
    final SimpleModule module = new SimpleModule()
                                    .addSerializer(MacAddress.class, new MacAddressToStringSerializer());
    mapper.registerModule(module);
    mapper.setDateFormat(this.simpleDateFormat);

    switch (context.getProperty(TIME_REPRESENTATION).getValue()) {
        case LOCAL_TZ:
            // set the mapper TZ to local TZ
            mapper.setTimeZone(TimeZone.getDefault());
            tzId = TimeZone.getDefault().getID();
            break;
        case UTC:
            // set the mapper TZ to local TZ
            mapper.setTimeZone(TimeZone.getTimeZone(UTC));
            tzId = UTC;
            break;
    }

}
 
Example #18
Source File: MonitorCenter.java    From wisdom with Apache License 2.0 6 votes vote down vote up
/**
 * When the monitor starts, we initializes and registers a JSON module handling the serialization of
 * the monitor extension.
 */
@Validate
public void start() {
    module = new SimpleModule(MonitorExtension.class.getName());
    module.addSerializer(MonitorExtension.class, new JsonSerializer<MonitorExtension>() {
        @Override
        public void serialize(MonitorExtension monitorExtension, JsonGenerator jsonGenerator,
                              SerializerProvider serializerProvider) throws IOException {
            jsonGenerator.writeStartObject();
            jsonGenerator.writeStringField("label", monitorExtension.label());
            jsonGenerator.writeStringField("url", monitorExtension.url());
            jsonGenerator.writeStringField("category", monitorExtension.category());
            jsonGenerator.writeEndObject();
        }
    });
    repository.register(module);
}
 
Example #19
Source File: ManagementConfiguration.java    From Spring-Boot-2.0-Cookbook-Second-Edition with MIT License 6 votes vote down vote up
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.
            json().
            //propertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE).
            propertyNamingStrategy(PropertyNamingStrategy.LOWER_CAMEL_CASE).
            //featuresToEnable(SerializationFeature.INDENT_OUTPUT).
            //featuresToEnable(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY).
            build();
    SimpleModule module = new SimpleModule();
    module.addSerializer(Set.class,
            new StdDelegatingSerializer(Set.class, new StdConverter<Set, List>() {
                @Override
                public List convert(Set value) {
                    LinkedList list = new LinkedList(value);
                    Collections.sort(list);
                    return list;
                }
            })
    );
    objectMapper.registerModule(module);
    HttpMessageConverter c = new MappingJackson2HttpMessageConverter(
            objectMapper
    );
    converters.add(c);
}
 
Example #20
Source File: JsonViewMessageConverter.java    From json-view with GNU General Public License v3.0 5 votes vote down vote up
public JsonViewMessageConverter(ObjectMapper mapper) {
  super();
  SimpleModule module = new SimpleModule();
  module.addSerializer(JsonView.class, this.serializer);
  mapper.registerModule(module);
  setObjectMapper(mapper);
}
 
Example #21
Source File: JsonDocumentUpdateMarshaller.java    From Cheddar with Apache License 2.0 5 votes vote down vote up
private JsonDocumentUpdateMarshaller() {
    mapper = new ObjectMapper();
    final SimpleModule module = new SimpleModule();
    module.addSerializer(Boolean.class, new BooleanLiteralSerializer());
    mapper.registerModule(module);
    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    mapper.registerModule(new JodaModule());
    mapper.setPropertyNamingStrategy(new LowerCasePropertyNamingStrategy());
}
 
Example #22
Source File: JacksonMapMarshaller.java    From okta-sdk-java with Apache License 2.0 5 votes vote down vote up
public JacksonMapMarshaller() {
    this.objectMapper = new ObjectMapper();
    this.objectMapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);

    SimpleModule simpleModule = new SimpleModule();
    simpleModule.addSerializer(new AbstractResourceSerializer(AbstractResource.class));
    this.objectMapper.registerModule(simpleModule);
}
 
Example #23
Source File: FlatteningSerializer.java    From botbuilder-java with MIT License 5 votes vote down vote up
/**
 * Gets a module wrapping this serializer as an adapter for the Jackson
 * ObjectMapper.
 *
 * @param mapper the object mapper for default serializations
 * @return a simple module to be plugged onto Jackson ObjectMapper.
 */
public static SimpleModule getModule(final ObjectMapper mapper) {
    SimpleModule module = new SimpleModule();
    module.setSerializerModifier(new BeanSerializerModifier() {
        @Override
        public JsonSerializer<?> modifySerializer(SerializationConfig config, BeanDescription beanDesc, JsonSerializer<?> serializer) {
            if (BeanSerializer.class.isAssignableFrom(serializer.getClass())) {
                return new FlatteningSerializer(beanDesc.getBeanClass(), serializer, mapper);
            }
            return serializer;
        }
    });
    return module;
}
 
Example #24
Source File: JacksonAutoConfiguration.java    From open-cloud with MIT License 5 votes vote down vote up
@Bean
@Primary
@ConditionalOnMissingBean(ObjectMapper.class)
public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
    objectMapper.setTimeZone(TimeZone.getTimeZone("GMT+8"));
    // 排序key
    objectMapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
    //忽略空bean转json错误
    objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    //忽略在json字符串中存在,在java类中不存在字段,防止错误。
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    /**
     * 序列换成json时,将所有的long变成string
     * 因为js中得数字类型不能包含所有的java long值
     */
    SimpleModule simpleModule = new SimpleModule();
    simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
    simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
    objectMapper.registerModule(simpleModule);
    // 兼容fastJson 的一些空值处理
    SerializerFeature[] features = new SerializerFeature[]{
            WriteNullListAsEmpty,
            WriteNullStringAsEmpty,
            WriteNullNumberAsZero,
            WriteNullBooleanAsFalse,
            WriteNullMapAsEmpty
    };
    objectMapper.setSerializerFactory(objectMapper.getSerializerFactory().withSerializerModifier(new FastJsonSerializerFeatureCompatibleForJackson(features)));
    log.info("ObjectMapper [{}]", objectMapper);
    return objectMapper;
}
 
Example #25
Source File: GooglePlusPersonSerDeIT.java    From streams with Apache License 2.0 5 votes vote down vote up
/**
 * setup.
 */
@BeforeClass
public void setup() {
  objectMapper = StreamsJacksonMapper.getInstance();
  SimpleModule simpleModule = new SimpleModule();
  simpleModule.addDeserializer(Person.class, new GPlusPersonDeserializer());
  objectMapper.registerModule(simpleModule);
  objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
 
Example #26
Source File: AbstractJsonGenerator.java    From protostuff-compiler with Apache License 2.0 5 votes vote down vote up
/**
 * Create new JSON generator instance.
 */
public AbstractJsonGenerator(OutputStreamFactory outputStreamFactory) {
    this.outputStreamFactory = outputStreamFactory;
    objectMapper = new ObjectMapper();
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
    SimpleModule module = new SimpleModule();
    module.addSerializer(Value.class, new ValueSerializer());
    objectMapper.registerModule(module);    
}
 
Example #27
Source File: JacksonUtil.java    From steady with Apache License 2.0 5 votes vote down vote up
/**
 * Serializes the given object to JSON, thereby using the given {@link StdSerializer}s and the given view {@link Class}.
 *
 * @param _object a {@link java.lang.Object} object.
 * @param _custom_serializers a {@link java.util.Map} object.
 * @param _view a {@link java.lang.Class} object.
 * @return a {@link java.lang.String} object.
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public static String asJsonString(final Object _object, final Map<Class<?>, StdSerializer<?>> _custom_serializers, final Class _view) {
       try {
           final ObjectMapper mapper = new ObjectMapper();
           
           // Register custom serializers
   		final SimpleModule module = new SimpleModule();
   		if(_custom_serializers!=null && !_custom_serializers.isEmpty()) {
   			for(Class clazz: _custom_serializers.keySet()) {
   				module.addSerializer(clazz, _custom_serializers.get(clazz));
   			}
   		}
   		mapper.registerModule(module);
           
   		String jsonContent = null;
   		if(_view==null) {
   			jsonContent = mapper.writeValueAsString(_object);
   		}
   		else {
   			jsonContent = mapper.writerWithView(_view).writeValueAsString(_object);
   		}
           return jsonContent;
       } catch (Exception e) {
           throw new RuntimeException(e);
       }
   }
 
Example #28
Source File: MinimalMapSerializerTest.java    From valdr-bean-validation with MIT License 5 votes vote down vote up
private String getJson() {
  ObjectMapper objectMapper = new ObjectMapper();

  SimpleModule module = new SimpleModule();
  module.addSerializer(MinimalMap.class, new MinimalMapSerializer());
  objectMapper.registerModule(module);

  ObjectWriter ow = objectMapper.writer().withDefaultPrettyPrinter();
  try {
    return ow.writeValueAsString(attributeMap);
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example #29
Source File: JacksonCustomizations.java    From sos with Apache License 2.0 5 votes vote down vote up
@Bean
SimpleModule ordersModule() {

	SimpleModule simpleModule = new SimpleModule();
	simpleModule.setMixInAnnotation(ProductInfo.ProductNumber.class, ProductNumberMixin.class);

	return simpleModule;
}
 
Example #30
Source File: StackTraceElementJsonMixInTest.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testFromJsonWithSimpleModule() throws Exception {
    final ObjectMapper mapper = new ObjectMapper();
    final SimpleModule module = new SimpleModule();
    module.addDeserializer(StackTraceElement.class, new Log4jStackTraceElementDeserializer());
    mapper.registerModule(module);
    final StackTraceElement expected = new StackTraceElement("package.SomeClass", "someMethod", "SomeClass.java", 123);
    final String s = this.aposToQuotes("{'class':'package.SomeClass','method':'someMethod','file':'SomeClass.java','line':123}");
    final StackTraceElement actual = mapper.readValue(s, StackTraceElement.class);
    Assert.assertEquals(expected, actual);
}