com.fasterxml.jackson.databind.ObjectMapper

Here are the examples of the java api class com.fasterxml.jackson.databind.ObjectMapper taken from open source projects.

1. HeroicMappers#config()

Project: heroic
Source File: HeroicMappers.java
View license
/**
     * Setup the ObjectMapper used to deserialize configuration files.
     *
     * @return
     */
public static ObjectMapper config() {
    final ObjectMapper m = new ObjectMapper(new YAMLFactory());
    m.addMixIn(ClusterDiscoveryModule.class, TypeNameMixin.class);
    m.addMixIn(RpcProtocolModule.class, TypeNameMixin.class);
    m.addMixIn(ConsumerModule.Builder.class, TypeNameMixin.class);
    m.addMixIn(MetadataModule.class, TypeNameMixin.class);
    m.addMixIn(SuggestModule.class, TypeNameMixin.class);
    m.addMixIn(MetricModule.class, TypeNameMixin.class);
    m.addMixIn(MetricGeneratorModule.class, TypeNameMixin.class);
    m.addMixIn(MetadataGenerator.class, TypeNameMixin.class);
    m.addMixIn(JettyConnectionFactory.Builder.class, TypeNameMixin.class);
    m.addMixIn(AnalyticsModule.Builder.class, TypeNameMixin.class);
    m.addMixIn(StatisticsModule.class, TypeNameMixin.class);
    m.registerModule(commonSerializers());
    /* support Optional */
    m.registerModule(new Jdk8Module());
    return m;
}

2. WorkflowReportJSON#makeObjectMapperForSave()

View license
protected static ObjectMapper makeObjectMapperForSave() {
    ObjectMapper om = new ObjectMapper();
    om.enable(INDENT_OUTPUT);
    om.disable(FAIL_ON_EMPTY_BEANS);
    om.enable(ORDER_MAP_ENTRIES_BY_KEYS);
    om.disable(WRITE_EMPTY_JSON_ARRAYS);
    om.disable(WRITE_NULL_MAP_VALUES);
    om.disable(WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED);
    om.disable(WRITE_DATES_AS_TIMESTAMPS);
    om.disable(WRITE_NULL_MAP_VALUES);
    om.addMixInAnnotations(Path.class, PathMixin.class);
    om.setSerializationInclusion(NON_NULL);
    return om;
}

3. JSONUtil#newMapper()

Project: ambrose
Source File: JSONUtil.java
View license
private static ObjectMapper newMapper() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    mapper.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false);
    mapper.configure(JsonGenerator.Feature.AUTO_CLOSE_JSON_CONTENT, false);
    mapper.disable(SerializationFeature.FLUSH_AFTER_WRITE_VALUE);
    mapper.disable(SerializationFeature.CLOSE_CLOSEABLE);
    mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
    mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    Reflections reflections = new Reflections("com.twitter.ambrose");
    Set<Class<? extends Job>> jobSubTypes = reflections.getSubTypesOf(Job.class);
    mapper.registerSubtypes(jobSubTypes.toArray(new Class<?>[jobSubTypes.size()]));
    return mapper;
}

4. HeroicMappers#json()

Project: heroic
Source File: HeroicMappers.java
View license
public static ObjectMapper json(final QueryParser parser) {
    final ObjectMapper mapper = new ObjectMapper();
    mapper.addMixIn(AggregationInstance.class, TypeNameMixin.class);
    mapper.addMixIn(Aggregation.class, TypeNameMixin.class);
    mapper.registerModule(new Jdk8Module().configureAbsentsAsNulls(true));
    mapper.registerModule(commonSerializers());
    mapper.registerModule(jsonSerializers());
    mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    mapper.registerModule(FilterRegistry.registry().module(parser));
    return mapper;
}

5. JsonHelpers#customizeObjectMapper()

Project: keywhiz
Source File: JsonHelpers.java
View license
/**
   * Customized ObjectMapper for common settings.
   *
   * @return customized object mapper
   */
private static ObjectMapper customizeObjectMapper() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new Jdk8Module());
    mapper.registerModule(new GuavaModule());
    mapper.registerModule(new LogbackModule());
    mapper.registerModule(new GuavaExtrasModule());
    mapper.registerModule(new FuzzyEnumModule());
    mapper.setPropertyNamingStrategy(new AnnotationSensitivePropertyNamingStrategy());
    mapper.setSubtypeResolver(new DiscoverableSubtypeResolver());
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    return mapper;
}

6. ObjectMapperFactory#createObjectMapper()

Project: qpid-java
Source File: ObjectMapperFactory.java
View license
public ObjectMapper createObjectMapper() {
    SimpleModule module = new SimpleModule();
    module.addDeserializer(PropertyValue.class, new PropertyValueDeserializer());
    module.addSerializer(SimplePropertyValue.class, new SimplePropertyValueSerializer());
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
    objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
    objectMapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
    objectMapper.configure(MapperFeature.AUTO_DETECT_GETTERS, false);
    objectMapper.registerModule(module);
    objectMapper.registerModule(module);
    return objectMapper;
}

7. EurekaJsonJacksonCodec#createObjectMapper()

Project: eureka
Source File: EurekaJsonJacksonCodec.java
View license
private ObjectMapper createObjectMapper(KeyFormatter keyFormatter, boolean compact, boolean wrapped) {
    ObjectMapper newMapper = new ObjectMapper();
    SimpleModule jsonModule = new SimpleModule();
    jsonModule.setSerializerModifier(EurekaJacksonJsonModifiers.createJsonSerializerModifier(keyFormatter, compact));
    newMapper.registerModule(jsonModule);
    newMapper.setSerializationInclusion(Include.NON_NULL);
    newMapper.configure(SerializationFeature.WRAP_ROOT_VALUE, wrapped);
    newMapper.configure(SerializationFeature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED, false);
    newMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, wrapped);
    newMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
    newMapper.addMixIn(Applications.class, ApplicationsJsonMixIn.class);
    if (compact) {
        addMiniConfig(newMapper);
    } else {
        newMapper.addMixIn(InstanceInfo.class, InstanceInfoJsonMixIn.class);
    }
    return newMapper;
}

8. JacksonTest#testMapTypeInfo()

Project: ode
Source File: JacksonTest.java
View license
@Test
public void testMapTypeInfo() throws JsonParseException, JsonMappingException, IOException {
    ObjectMapper mapper = new ObjectMapper(new SmileFactory());
    mapper.setSerializerFactory(TypeBeanSerializerFactory.instance);
    mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    C c = new C();
    QName qname = new QName("uri", "localtest");
    c.map.put(qname, qname);
    mapper.writeValue(os, c);
    ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
    ObjectMapper m2 = new ObjectMapper(new SmileFactory());
    m2.setSerializerFactory(TypeBeanSerializerFactory.instance);
    m2.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    C de = m2.readValue(is, C.class);
    assertEquals(c.map, de.map);
}

9. JacksonTest#testSmileFormat()

Project: ode
Source File: JacksonTest.java
View license
@Test
public void testSmileFormat() throws JsonGenerationException, JsonMappingException, IOException {
    ObjectMapper mapper = new ObjectMapper(new SmileFactory());
    D d = new D();
    d.next = d;
    mapper.setSerializerFactory(TypeBeanSerializerFactory.instance);
    mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    mapper.writeValue(os, d);
    ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
    ObjectMapper m2 = new ObjectMapper(new SmileFactory());
    m2.setSerializerFactory(TypeBeanSerializerFactory.instance);
    m2.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    D de = m2.readValue(is, D.class);
    assertEquals(D.class, de.next.getClass());
}

10. ConfigSupport#createMapper()

Project: redisson
Source File: ConfigSupport.java
View license
private ObjectMapper createMapper(JsonFactory mapping) {
    ObjectMapper mapper = new ObjectMapper(mapping);
    mapper.addMixIn(MasterSlaveServersConfig.class, MasterSlaveServersConfigMixIn.class);
    mapper.addMixIn(SingleServerConfig.class, SingleSeverConfigMixIn.class);
    mapper.addMixIn(Config.class, ConfigMixIn.class);
    mapper.addMixIn(Codec.class, ClassMixIn.class);
    mapper.addMixIn(LoadBalancer.class, ClassMixIn.class);
    FilterProvider filterProvider = new SimpleFilterProvider().addFilter("classFilter", SimpleBeanPropertyFilter.filterOutAllExcept());
    mapper.setFilterProvider(filterProvider);
    mapper.setSerializationInclusion(Include.NON_NULL);
    return mapper;
}

11. MessagePackGeneratorTest#testWritePrimitiveObjectViaObjectMapper()

View license
@Test
public void testWritePrimitiveObjectViaObjectMapper() throws Exception {
    File tempFile = createTempFile();
    OutputStream out = new FileOutputStream(tempFile);
    ObjectMapper objectMapper = new ObjectMapper(new MessagePackFactory());
    objectMapper.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false);
    objectMapper.writeValue(out, 1);
    objectMapper.writeValue(out, "two");
    objectMapper.writeValue(out, 3.14);
    objectMapper.writeValue(out, Arrays.asList(4));
    objectMapper.writeValue(out, 5L);
    MessageUnpacker unpacker = MessagePack.newDefaultUnpacker(new FileInputStream(tempFile));
    assertEquals(1, unpacker.unpackInt());
    assertEquals("two", unpacker.unpackString());
    assertEquals(3.14, unpacker.unpackFloat(), 0.0001);
    assertEquals(1, unpacker.unpackArrayHeader());
    assertEquals(4, unpacker.unpackInt());
    assertEquals(5, unpacker.unpackLong());
}

12. JacksonConverterFactoryTest#setUp()

View license
@Before
public void setUp() {
    SimpleModule module = new SimpleModule();
    module.addSerializer(AnInterface.class, new AnInterfaceSerializer());
    module.addDeserializer(AnInterface.class, new AnInterfaceDeserializer());
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(module);
    mapper.configure(MapperFeature.AUTO_DETECT_GETTERS, false);
    mapper.configure(MapperFeature.AUTO_DETECT_SETTERS, false);
    mapper.configure(MapperFeature.AUTO_DETECT_IS_GETTERS, false);
    mapper.setVisibilityChecker(mapper.getSerializationConfig().getDefaultVisibilityChecker().withFieldVisibility(JsonAutoDetect.Visibility.ANY));
    Retrofit retrofit = new Retrofit.Builder().baseUrl(server.url("/")).addConverterFactory(JacksonConverterFactory.create(mapper)).build();
    service = retrofit.create(Service.class);
}

13. ObjectMapperFactory#create()

View license
private static ObjectMapper create(boolean indent) {
    ObjectMapper objectMapper = new ObjectMapper();
    // This will cause the objectmapper to not close the underlying output stream
    objectMapper.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false);
    objectMapper.configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, false);
    objectMapper.registerModule(new MetricsModule(TimeUnit.SECONDS, TimeUnit.SECONDS, false, MetricFilter.ALL));
    SimpleModule module = new SimpleModule();
    module.addDeserializer(FieldJson.class, new FieldDeserializer());
    module.addSerializer(ExtendedMeter.class, new ExtendedMeterSerializer(TimeUnit.SECONDS));
    module.addDeserializer(ErrorMessage.class, new ErrorMessageDeserializer());
    module.addSerializer(BigDecimal.class, new ToStringSerializer());
    objectMapper.registerModule(module);
    if (indent) {
        objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
    }
    return objectMapper;
}

14. ObjectMapperFactory#makeObjectMapper()

Project: petri
Source File: ObjectMapperFactory.java
View license
public static ObjectMapper makeObjectMapper() {
    final ObjectMapper objectMapper = new ObjectMapper();
    final SimpleModule module = new SimpleModule(MODULE_NAME, MODULE_VERSION);
    module.addDeserializer(DateTime.class, new TimeZoneAwareDateTimeDeserializer());
    module.addSerializer(DateTime.class, new DateTimeSerializer());
    objectMapper.registerModule(module);
    objectMapper.registerModule(new DefaultScalaModule());
    objectMapper.setTimeZone(TimeZone.getTimeZone("UTC"));
    objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    return objectMapper;
}

15. Serializers#lenient()

Project: proctor
Source File: Serializers.java
View license
public static ObjectMapper lenient() {
    final ObjectMapper mapper = new ObjectMapper();
    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    mapper.configure(Feature.ALLOW_COMMENTS, true);
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    final SimpleModule module = new SimpleModule();
    final PlainNumericSerializer plainNumericSerializer = new PlainNumericSerializer();
    module.addSerializer(double.class, plainNumericSerializer);
    module.addSerializer(Double.class, plainNumericSerializer);
    mapper.registerModule(module);
    return mapper;
}

16. Serializers#strict()

Project: proctor
Source File: Serializers.java
View license
/**
     * Get an {@link ObjectMapper} configured to do things as we want
     */
@Nonnull
public static ObjectMapper strict() {
    final ObjectMapper mapper = new ObjectMapper();
    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    mapper.configure(Feature.ALLOW_COMMENTS, true);
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);
    final SimpleModule module = new SimpleModule();
    final PlainNumericSerializer plainNumericSerializer = new PlainNumericSerializer();
    module.addSerializer(double.class, plainNumericSerializer);
    module.addSerializer(Double.class, plainNumericSerializer);
    mapper.registerModule(module);
    return mapper;
}

17. SingularityRunnerBaseModule#providesYamlMapper()

View license
@Provides
@Singleton
@Named(YAML)
public ObjectMapper providesYamlMapper() {
    final YAMLFactory yamlFactory = new YAMLFactory();
    yamlFactory.disable(YAMLGenerator.Feature.WRITE_DOC_START_MARKER);
    final ObjectMapper mapper = new ObjectMapper(yamlFactory);
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.registerModule(new GuavaModule());
    mapper.registerModule(new ProtobufModule());
    return mapper;
}

18. IssueTrackerConfiguration#jacksonObjectMapper()

View license
@Bean
ObjectMapper jacksonObjectMapper() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.setSerializationInclusion(Include.NON_NULL);
    mapper.registerModule(new ParameterNamesModule(Mode.PROPERTIES));
    mapper.registerModule(new SyntheticLambdaFactoryMethodIgnoringModule());
    return mapper;
}

19. GoogleTemplate#getMessageConverters()

View license
@Override
protected List<HttpMessageConverter<?>> getMessageConverters() {
    MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(FAIL_ON_UNKNOWN_PROPERTIES, false);
    objectMapper.configure(WRITE_DATES_AS_TIMESTAMPS, false);
    objectMapper.configure(FAIL_ON_EMPTY_BEANS, false);
    objectMapper.setSerializationInclusion(NON_NULL);
    jsonConverter.setObjectMapper(objectMapper);
    FormHttpMessageConverter formHttpMessageConverter = new FormHttpMessageConverter();
    formHttpMessageConverter.addPartConverter(jsonConverter);
    List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
    messageConverters.add(jsonConverter);
    messageConverters.add(new ByteArrayHttpMessageConverter());
    messageConverters.add(formHttpMessageConverter);
    messageConverters.add(new ResourceHttpMessageConverter());
    return messageConverters;
}

20. JacksonModule#createJacksonJsonProvider()

Project: wasabi
Source File: JacksonModule.java
View license
private JacksonJsonProvider createJacksonJsonProvider() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    mapper.setSerializationInclusion(ALWAYS);
    mapper.registerModule(new SimpleModule() {

        {
            addSerializer(Double.class, new NaNSerializerDouble());
            addSerializer(Float.class, new NaNSerializerFloat());
            addDeserializer(Timestamp.class, new SQLTimestampDeserializer());
            addDeserializer(Experiment.State.class, new ExperimentStateDeserializer());
            addSerializer(new UpperCaseToStringSerializer<>(Experiment.State.class));
        }
    });
    SimpleDateFormat iso8601Formatter = new SimpleDateFormat(ISO8601_DATE_FORMAT);
    iso8601Formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
    mapper.setDateFormat(iso8601Formatter);
    JacksonJsonProvider provider = new WasabiJacksonJsonProvider();
    provider.setMapper(mapper);
    return provider;
}

21. ContentParserTest#testParseJson()

View license
@Test
public void testParseJson() throws Exception {
    ObjectMapper jsonObjectMapper = new ObjectMapper();
    jsonObjectMapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
    jsonObjectMapper.configure(JsonParser.Feature.ALLOW_YAML_COMMENTS, true);
    // not by default configured, but much easier for unit-testing Java embedded JSON Strings
    jsonObjectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
    ContentParser contentParser = new ContentParser(jsonObjectMapper);
    String jsonObjectString = "{ /*comment*/ 'string' : 'foobar', 'int' : 1, 'boolean' : false, 'null' : null }";
    LinkedHashMap<String, Object> jsonObject = new LinkedHashMap<>();
    jsonObject.put("string", "foobar");
    jsonObject.put("int", new Integer(1));
    jsonObject.put("boolean", Boolean.FALSE);
    jsonObject.put("null", null);
    Assert.assertEquals(jsonObject, contentParser.parseJson(jsonObjectString));
    String jsonArrayString = "[" + jsonObjectString + "," + "# yaml comment\n" + jsonObjectString + "]";
    ArrayList<Object> jsonArray = new ArrayList<>(2);
    jsonArray.add(jsonObject);
    jsonArray.add(jsonObject);
    Assert.assertEquals(jsonArray, contentParser.parseJson(jsonArrayString));
}

22. TestUtil#convertObjectToJsonBytes()

Project: expper
Source File: TestUtil.java
View license
/**
     * Convert an object to JSON byte array.
     *
     * @param object
     *            the object to convert
     * @return the JSON byte array
     * @throws IOException
     */
public static byte[] convertObjectToJsonBytes(Object object) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    JavaTimeModule module = new JavaTimeModule();
    module.addSerializer(OffsetDateTime.class, JSR310DateTimeSerializer.INSTANCE);
    module.addSerializer(ZonedDateTime.class, JSR310DateTimeSerializer.INSTANCE);
    module.addSerializer(LocalDateTime.class, JSR310DateTimeSerializer.INSTANCE);
    module.addSerializer(Instant.class, JSR310DateTimeSerializer.INSTANCE);
    module.addDeserializer(LocalDate.class, JSR310LocalDateDeserializer.INSTANCE);
    mapper.registerModule(module);
    return mapper.writeValueAsBytes(object);
}

23. CliModule#generalMapper()

Project: keywhiz
Source File: CliModule.java
View license
@Provides
public ObjectMapper generalMapper() {
    /**
     * Customizes ObjectMapper for common settings.
     *
     * @param objectMapper to be customized
     * @return customized input factory
     */
    ObjectMapper objectMapper = Jackson.newObjectMapper();
    objectMapper.registerModule(new Jdk8Module());
    objectMapper.registerModules(new JavaTimeModule());
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    return objectMapper;
}

24. MessagePackGeneratorTest#testDisableFeatureAutoCloseTarget()

View license
@Test
public void testDisableFeatureAutoCloseTarget() throws Exception {
    File tempFile = createTempFile();
    OutputStream out = new FileOutputStream(tempFile);
    MessagePackFactory messagePackFactory = new MessagePackFactory();
    ObjectMapper objectMapper = new ObjectMapper(messagePackFactory);
    objectMapper.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false);
    List<Integer> integers = Arrays.asList(1);
    objectMapper.writeValue(out, integers);
    objectMapper.writeValue(out, integers);
    out.close();
    MessageUnpacker unpacker = MessagePack.newDefaultUnpacker(new FileInputStream(tempFile));
    assertEquals(1, unpacker.unpackArrayHeader());
    assertEquals(1, unpacker.unpackInt());
    assertEquals(1, unpacker.unpackArrayHeader());
    assertEquals(1, unpacker.unpackInt());
}

25. BsonGeneratorTest#generateAndParse()

Project: bson4jackson
Source File: BsonGeneratorTest.java
View license
private BSONObject generateAndParse(Map<String, Object> data, BsonGenerator.Feature... featuresToEnable) throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    BsonFactory bsonFactory = new BsonFactory();
    if (featuresToEnable != null) {
        for (BsonGenerator.Feature fe : featuresToEnable) {
            bsonFactory.enable(fe);
        }
    }
    ObjectMapper om = new ObjectMapper(bsonFactory);
    om.registerModule(new BsonModule());
    om.writeValue(baos, data);
    byte[] r = baos.toByteArray();
    ByteArrayInputStream bais = new ByteArrayInputStream(r);
    BSONDecoder decoder = new BasicBSONDecoder();
    return decoder.readObject(bais);
}

26. BsonParserTest#parseBig()

Project: bson4jackson
Source File: BsonParserTest.java
View license
@Test
public void parseBig() throws Exception {
    BSONObject o = new BasicBSONObject();
    o.put("Double", 5.0);
    o.put("Int32", 1234);
    BSONEncoder enc = new BasicBSONEncoder();
    byte[] b = enc.encode(o);
    ByteArrayInputStream bais = new ByteArrayInputStream(b);
    ObjectMapper mapper = new ObjectMapper(new BsonFactory());
    mapper.configure(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS, true);
    mapper.configure(DeserializationFeature.USE_BIG_INTEGER_FOR_INTS, true);
    Map<?, ?> data = mapper.readValue(bais, Map.class);
    assertEquals(BigDecimal.class, data.get("Double").getClass());
    assertEquals(BigInteger.class, data.get("Int32").getClass());
}

27. BsonSerializersTest#generateAndParse()

View license
private static Object generateAndParse(Object data) throws Exception {
    Map<String, Object> m = new LinkedHashMap<String, Object>();
    m.put("data", data);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectMapper om = new ObjectMapper(new BsonFactory());
    om.registerModule(new BsonModule());
    om.writeValue(baos, m);
    byte[] r = baos.toByteArray();
    ByteArrayInputStream bais = new ByteArrayInputStream(r);
    BSONDecoder decoder = new BasicBSONDecoder();
    BSONObject bo = decoder.readObject(bais);
    return bo.get("data");
}

28. RestSwaggerReaderApiDocsOverrideTest#testReaderRead()

View license
@Test
public void testReaderRead() throws Exception {
    BeanConfig config = new BeanConfig();
    config.setHost("localhost:8080");
    config.setSchemes(new String[] { "http" });
    config.setBasePath("/api");
    RestSwaggerReader reader = new RestSwaggerReader();
    Swagger swagger = reader.read(context.getRestDefinitions(), null, config, context.getName(), new DefaultClassResolver());
    assertNotNull(swagger);
    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    String json = mapper.writeValueAsString(swagger);
    log.info(json);
    assertFalse(json.contains("\"/hello/bye\""));
    assertFalse(json.contains("\"summary\" : \"To update the greeting message\""));
    assertTrue(json.contains("\"/hello/bye/{name}\""));
    assertFalse(json.contains("\"/hello/hi/{name}\""));
    context.stop();
}

29. ProcessingResult#serializeJson()

Project: carrot2
Source File: ProcessingResult.java
View license
/**
     * Serializes this processing result as JSON to the provided <code>writer</code>.
     * Documents, clusters and other attributes can be included or skipped in the output
     * as requested.
     * 
     * @param writer the writer to serialize this processing result to. The writer will
     *            <strong>not</strong> be closed.
     * @param callback JavaScript function name in which to wrap the JSON response or
     *            <code>null</code>.
     * @param indent if <code>true</code>, the output JSON will be pretty-printed
     * @param saveDocuments if <code>false</code>, documents will not be serialized.
     * @param saveClusters if <code>false</code>, clusters will not be serialized
     * @param saveOtherAttributes if <code>false</code>, other attributes will not be
     *            serialized
     * @throws IOException in case of any problems with serialization
     */
public void serializeJson(Writer writer, String callback, boolean indent, boolean saveDocuments, boolean saveClusters, boolean saveOtherAttributes) throws IOException {
    final ObjectMapper mapper = new ObjectMapper();
    mapper.getFactory().disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET);
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    if (StringUtils.isNotBlank(callback)) {
        writer.write(callback + "(");
    }
    final Map<String, Object> attrs = prepareAttributesForSerialization(saveDocuments, saveClusters, saveOtherAttributes);
    mapper.writeValue(writer, attrs);
    if (StringUtils.isNotBlank(callback)) {
        writer.write(");");
    }
}

30. DefaultTypingTest#roundtrip()

Project: immutables
Source File: DefaultTypingTest.java
View license
@Test
public void roundtrip() throws IOException {
    final ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.enableDefaultTyping();
    objectMapper.registerModule(new GuavaModule());
    ImmutableOuterObject outer = ImmutableOuterObject.builder().emptyObject(ImmutableEmptyObject.builder().build()).build();
    String serialized = objectMapper.writeValueAsString(outer);
    check(objectMapper.readValue(serialized, ImmutableOuterObject.class)).is(outer);
}

31. JsonMapper#createObjectMapper()

Project: isis
Source File: JsonMapper.java
View license
private static ObjectMapper createObjectMapper(PrettyPrinting prettyPrinting) {
    final ObjectMapper objectMapper = new ObjectMapper();
    final SimpleModule jsonModule = new SimpleModule("json", new Version(1, 0, 0, null, "org.apache", "isis"));
    jsonModule.addDeserializer(JsonRepresentation.class, new JsonRepresentationDeserializer());
    jsonModule.addSerializer(JsonRepresentation.class, new JsonRepresentationSerializer());
    objectMapper.registerModule(jsonModule);
    if (prettyPrinting == PrettyPrinting.ENABLE) {
        objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
    }
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    return objectMapper;
}

32. CatalogClient#getRestTemplate()

Project: microservice
Source File: CatalogClient.java
View license
protected RestTemplate getRestTemplate() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.registerModule(new Jackson2HalModule());
    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    converter.setSupportedMediaTypes(Arrays.asList(MediaTypes.HAL_JSON));
    converter.setObjectMapper(mapper);
    return new RestTemplate(Collections.<HttpMessageConverter<?>>singletonList(converter));
}

33. CustomerClient#getRestTemplate()

Project: microservice
Source File: CustomerClient.java
View license
protected RestTemplate getRestTemplate() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.registerModule(new Jackson2HalModule());
    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    converter.setSupportedMediaTypes(Arrays.asList(MediaTypes.HAL_JSON));
    converter.setObjectMapper(mapper);
    return new RestTemplate(Collections.<HttpMessageConverter<?>>singletonList(converter));
}

34. CatalogClient#getRestTemplate()

Project: microservice
Source File: CatalogClient.java
View license
protected RestTemplate getRestTemplate() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.registerModule(new Jackson2HalModule());
    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    converter.setSupportedMediaTypes(Arrays.asList(MediaTypes.HAL_JSON));
    converter.setObjectMapper(mapper);
    return new RestTemplate(Collections.<HttpMessageConverter<?>>singletonList(converter));
}

35. CustomerClient#getRestTemplate()

Project: microservice
Source File: CustomerClient.java
View license
protected RestTemplate getRestTemplate() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.registerModule(new Jackson2HalModule());
    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    converter.setSupportedMediaTypes(Arrays.asList(MediaTypes.HAL_JSON));
    converter.setObjectMapper(mapper);
    return new RestTemplate(Collections.<HttpMessageConverter<?>>singletonList(converter));
}

36. CatalogClient#getRestTemplate()

View license
protected RestTemplate getRestTemplate() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.registerModule(new Jackson2HalModule());
    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    converter.setSupportedMediaTypes(Arrays.asList(MediaTypes.HAL_JSON));
    converter.setObjectMapper(mapper);
    return new RestTemplate(Collections.<HttpMessageConverter<?>>singletonList(converter));
}

37. CustomerClient#getRestTemplate()

View license
protected RestTemplate getRestTemplate() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.registerModule(new Jackson2HalModule());
    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    converter.setSupportedMediaTypes(Arrays.asList(MediaTypes.HAL_JSON));
    converter.setObjectMapper(mapper);
    return new RestTemplate(Collections.<HttpMessageConverter<?>>singletonList(converter));
}

38. CatalogClient#getRestTemplate()

View license
protected RestTemplate getRestTemplate() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.registerModule(new Jackson2HalModule());
    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    converter.setSupportedMediaTypes(Arrays.asList(MediaTypes.HAL_JSON));
    converter.setObjectMapper(mapper);
    return new RestTemplate(Collections.<HttpMessageConverter<?>>singletonList(converter));
}

39. CustomerClient#getRestTemplate()

View license
protected RestTemplate getRestTemplate() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.registerModule(new Jackson2HalModule());
    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    converter.setSupportedMediaTypes(Arrays.asList(MediaTypes.HAL_JSON));
    converter.setObjectMapper(mapper);
    return new RestTemplate(Collections.<HttpMessageConverter<?>>singletonList(converter));
}

40. MessagePackGeneratorTest#testComplexTypeKeyWithV06Format()

View license
@Test
public void testComplexTypeKeyWithV06Format() throws IOException {
    HashMap<TinyPojo, Integer> map = new HashMap<TinyPojo, Integer>();
    TinyPojo pojo = new TinyPojo();
    pojo.t = "foo";
    map.put(pojo, 42);
    ObjectMapper objectMapper = new ObjectMapper(new MessagePackFactory());
    objectMapper.setAnnotationIntrospector(new JsonArrayFormat());
    objectMapper.setSerializerFactory(new MessagePackSerializerFactory());
    byte[] bytes = objectMapper.writeValueAsBytes(map);
    MessageUnpacker unpacker = MessagePack.newDefaultUnpacker(bytes);
    assertThat(unpacker.unpackMapHeader(), is(1));
    assertThat(unpacker.unpackArrayHeader(), is(1));
    assertThat(unpacker.unpackString(), is("foo"));
    assertThat(unpacker.unpackInt(), is(42));
}

41. JsonReferenceSerializationTest#createMapper()

View license
private ObjectMapper createMapper() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setVisibility(mapper.getSerializationConfig().getDefaultVisibilityChecker().withFieldVisibility(JsonAutoDetect.Visibility.ANY).withGetterVisibility(JsonAutoDetect.Visibility.NONE).withIsGetterVisibility(JsonAutoDetect.Visibility.NONE).withSetterVisibility(JsonAutoDetect.Visibility.NONE).withCreatorVisibility(JsonAutoDetect.Visibility.NONE));
    mapper.registerModule(new ActorReferenceModule(factory));
    return mapper;
}

42. PluginDisableIT#test()

Project: pinpoint
Source File: PluginDisableIT.java
View license
@Test
public void test() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("name", "jackson");
    mapper.writeValueAsString(map);
    mapper.writeValueAsBytes(map);
    ObjectWriter writer = mapper.writer();
    writer.writeValueAsString(map);
    writer.writeValueAsBytes(map);
    PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
    verifier.printCache();
    verifier.verifyTraceCount(0);
}

43. MetaDataServlet#doGetWithSubjectAndActor()

Project: qpid-java
Source File: MetaDataServlet.java
View license
@Override
protected void doGetWithSubjectAndActor(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("application/json");
    response.setStatus(HttpServletResponse.SC_OK);
    Map<String, Map> classToDataMap = new TreeMap<>();
    for (Class<? extends ConfiguredObject> clazz : _instance.getSupportedCategories()) {
        classToDataMap.put(clazz.getSimpleName(), processCategory(clazz));
    }
    final OutputStream stream = getOutputStream(request, response);
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
    mapper.writeValue(stream, classToDataMap);
    response.setContentType("application/json");
    response.setStatus(HttpServletResponse.SC_OK);
}

44. ApplicationConfiguration#repositoryPopulator()

View license
/**
	 * Read JSON data from disk and insert those stores.
	 * 
	 * @return
	 */
@Bean
public AbstractRepositoryPopulatorFactoryBean repositoryPopulator() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.addMixIn(GeoJsonPoint.class, GeoJsonPointMixin.class);
    mapper.configure(FAIL_ON_UNKNOWN_PROPERTIES, false);
    Jackson2RepositoryPopulatorFactoryBean factoryBean = new Jackson2RepositoryPopulatorFactoryBean();
    factoryBean.setResources(new Resource[] { new ClassPathResource("starbucks-in-nyc.json") });
    factoryBean.setMapper(mapper);
    return factoryBean;
}

45. AnalyticsIncorporationComponentEventSerializationTest#testMixinNoCopy()

View license
@Test
public void testMixinNoCopy() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    mapper.findAndRegisterModules();
    mapper.addMixInAnnotations(Object.class, PortletRenderExecutionEventFilterMixIn.class);
    final FilterProvider filterProvider = new SimpleFilterProvider().addFilter(PortletRenderExecutionEventFilterMixIn.FILTER_NAME, SimpleBeanPropertyFilter.filterOutAllExcept("fname", "executionTimeNano", "parameters"));
    final ObjectWriter portletEventWriter = mapper.writer(filterProvider);
    final String result = portletEventWriter.writeValueAsString(createEvent());
    assertEquals("{\"@c\":\".PortletRenderExecutionEvent\",\"fname\":\"fname1\",\"executionTimeNano\":123450000,\"parameters\":{}}", result);
}

46. AnalyticsIncorporationComponentEventSerializationTest#testMixinWithCopy()

View license
/**
     * Fails as actual output is:
     * {"@c":".PortletRenderExecutionEvent","timestamp":1371671516798,"serverId":"example.com","eventSessionId":"1234567890123_system_AAAAAAAAAAA","userName":"system","fname":"fname1","executionTimeNano":123450000,"parameters":{},"targeted":false,"usedPortalCache":false}
     */
@Ignore
@Test
public void testMixinWithCopy() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    mapper.findAndRegisterModules();
    //Clone from "shared" ObjectMapper
    mapper = mapper.copy();
    mapper.addMixInAnnotations(Object.class, PortletRenderExecutionEventFilterMixIn.class);
    final FilterProvider filterProvider = new SimpleFilterProvider().addFilter(PortletRenderExecutionEventFilterMixIn.FILTER_NAME, SimpleBeanPropertyFilter.filterOutAllExcept("fname", "executionTimeNano", "parameters"));
    final ObjectWriter portletEventWriter = mapper.writer(filterProvider);
    final String result = portletEventWriter.writeValueAsString(createEvent());
    assertEquals("{\"@c\":\".PortletRenderExecutionEvent\",\"fname\":\"fname1\",\"executionTimeNano\":123450000,\"parameters\":{}}", result);
}

47. JsonTest#main()

Project: weixin
Source File: JsonTest.java
View license
public static void main(String[] args) throws Exception {
    List<DeviceIdentifier> deviceIdentifierList = new ArrayList<DeviceIdentifier>();
    DeviceIdentifier dd = new DeviceIdentifier();
    dd.setDevice_id(10100);
    dd.setUuid("FDA50693-A4E2-4FB1-AFCF-C6EB07647825");
    dd.setMajor(10001);
    dd.setMinor(10002);
    deviceIdentifierList.add(dd);
    deviceIdentifierList.add(dd);
    System.out.println(JsonUtils.toJson(deviceIdentifierList));
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
    mapper.configure(JsonParser.Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER, true);
    String json = "{\"city\":\"??T\\n\",\"province\":\"???l_\"}";
    System.out.println(mapper.readValue(json, Map.class));
    System.out.println(JsonUtils.parse(json, Map.class));
}

48. DropwizardModule#provideObjectMapper()

Project: airpal
Source File: DropwizardModule.java
View license
@Singleton
@Provides
protected ObjectMapper provideObjectMapper() {
    ObjectMapper mapper = environment.getObjectMapper();
    mapper.registerSubtypes(new NamedType(CSVPersistentOutput.class, "csv"), new NamedType(HiveTablePersistentOutput.class, "hive"));
    Rosetta.getMapper().disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
    Rosetta.getMapper().enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES);
    return mapper;
}

49. RedisKeyValueStateProvider#getStateConfig()

View license
StateConfig getStateConfig(Map stormConf) throws Exception {
    StateConfig stateConfig = null;
    String providerConfig = null;
    ObjectMapper mapper = new ObjectMapper();
    mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
    if (stormConf.containsKey(org.apache.storm.Config.TOPOLOGY_STATE_PROVIDER_CONFIG)) {
        providerConfig = (String) stormConf.get(org.apache.storm.Config.TOPOLOGY_STATE_PROVIDER_CONFIG);
        stateConfig = mapper.readValue(providerConfig, StateConfig.class);
    } else {
        stateConfig = new StateConfig();
    }
    return stateConfig;
}

50. VirtualMachinesImpl#capture()

View license
@Override
public String capture(String groupName, String name, String containerName, boolean overwriteVhd) throws CloudException, IOException, InterruptedException {
    VirtualMachineCaptureParametersInner parameters = new VirtualMachineCaptureParametersInner();
    parameters.withDestinationContainerName(containerName);
    parameters.withOverwriteVhds(overwriteVhd);
    ServiceResponse<VirtualMachineCaptureResultInner> captureResult = this.innerCollection.capture(groupName, name, parameters);
    ObjectMapper mapper = new ObjectMapper();
    //Object to JSON string
    return mapper.writeValueAsString(captureResult.getBody().output());
}

51. RuleFieldExtractionUtility#convertJsonToDataWrapper()

View license
/**
     * Takes a JSON string that came from the frontend form submission and deserializes it into its {@link DataWrapper} dto
     * representation so that it can be converted to an MVEL expression
     * @param json
     * @return
     */
public DataWrapper convertJsonToDataWrapper(String json) {
    ObjectMapper mapper = new ObjectMapper();
    DataDTODeserializer dtoDeserializer = new DataDTODeserializer();
    SimpleModule module = new SimpleModule("DataDTODeserializerModule", new Version(1, 0, 0, null));
    module.addDeserializer(DataDTO.class, dtoDeserializer);
    mapper.registerModule(module);
    if (json == null || "[]".equals(json)) {
        return null;
    }
    try {
        return mapper.readValue(json, DataWrapper.class);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

52. FormBuilderServiceImpl#convertJsonToDataWrapper()

View license
/**
     * When using Thymeleaf, we need to convert the JSON string back to
     * a DataWrapper object because Thymeleaf escapes JSON strings.
     * Thymeleaf uses it's own object de-serializer
     * see: https://github.com/thymeleaf/thymeleaf/issues/84
     * see: http://forum.thymeleaf.org/Spring-Javascript-and-escaped-JSON-td4024739.html
     * @param json
     * @return DataWrapper
     * @throws IOException
     */
protected DataWrapper convertJsonToDataWrapper(String json) {
    ObjectMapper mapper = new ObjectMapper();
    DataDTODeserializer dtoDeserializer = new DataDTODeserializer();
    SimpleModule module = new SimpleModule("DataDTODeserializerModule", new Version(1, 0, 0, null, null, null));
    module.addDeserializer(DataDTO.class, dtoDeserializer);
    mapper.registerModule(module);
    try {
        return mapper.readValue(json, DataWrapper.class);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

53. RuleFieldExtractionUtility#convertJsonToDataWrapper()

View license
/**
     * Takes a JSON string that came from the frontend form submission and deserializes it into its {@link DataWrapper} dto
     * representation so that it can be converted to an MVEL expression
     * @param json
     * @return
     */
public DataWrapper convertJsonToDataWrapper(String json) {
    ObjectMapper mapper = new ObjectMapper();
    DataDTODeserializer dtoDeserializer = new DataDTODeserializer();
    SimpleModule module = new SimpleModule("DataDTODeserializerModule", new Version(1, 0, 0, null));
    module.addDeserializer(DataDTO.class, dtoDeserializer);
    mapper.registerModule(module);
    if (json == null || "[]".equals(json)) {
        return null;
    }
    try {
        return mapper.readValue(json, DataWrapper.class);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

54. FormBuilderServiceImpl#convertJsonToDataWrapper()

View license
/**
     * When using Thymeleaf, we need to convert the JSON string back to
     * a DataWrapper object because Thymeleaf escapes JSON strings.
     * Thymeleaf uses it's own object de-serializer
     * see: https://github.com/thymeleaf/thymeleaf/issues/84
     * see: http://forum.thymeleaf.org/Spring-Javascript-and-escaped-JSON-td4024739.html
     * @param json
     * @return DataWrapper
     * @throws IOException
     */
protected DataWrapper convertJsonToDataWrapper(String json) {
    ObjectMapper mapper = new ObjectMapper();
    DataDTODeserializer dtoDeserializer = new DataDTODeserializer();
    SimpleModule module = new SimpleModule("DataDTODeserializerModule", new Version(1, 0, 0, null, null, null));
    module.addDeserializer(DataDTO.class, dtoDeserializer);
    mapper.registerModule(module);
    try {
        return mapper.readValue(json, DataWrapper.class);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

55. BsonParserTest#parseBsonObject()

Project: bson4jackson
Source File: BsonParserTest.java
View license
private <T> T parseBsonObject(BSONObject o, Class<T> cls, Module... modules) throws IOException {
    BSONEncoder enc = new BasicBSONEncoder();
    byte[] b = enc.encode(o);
    ByteArrayInputStream bais = new ByteArrayInputStream(b);
    BsonFactory fac = new BsonFactory();
    ObjectMapper mapper = new ObjectMapper(fac);
    if (modules != null) {
        for (Module mod : modules) {
            mapper.registerModule(mod);
        }
    }
    fac.setCodec(mapper);
    return mapper.readValue(bais, cls);
}

56. BsonParserTest#parseRootObjectAsArray()

Project: bson4jackson
Source File: BsonParserTest.java
View license
/**
	 * Tests if a root object is not accidentally parsed as an array
	 * @throws Exception if something went wrong
	 */
@Test(expected = JsonMappingException.class)
public void parseRootObjectAsArray() throws Exception {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    BsonFactory bsonFactory = new BsonFactory();
    BsonGenerator generator = bsonFactory.createGenerator(out);
    generator.writeStartObject();
    generator.writeStringField("myField", "myValue");
    generator.writeEndObject();
    generator.close();
    InputStream is = new ByteArrayInputStream(out.toByteArray());
    ObjectMapper mapper = new ObjectMapper(bsonFactory);
    bsonFactory.setCodec(mapper);
    mapper.readValue(is, String[].class);
}

57. BsonDeserializersTest#generateAndParse()

View license
private static <T> T generateAndParse(Object o, Class<T> cls) throws Exception {
    BSONObject bo = new BasicBSONObject();
    //that's why all properties of classes in TC must be named 'obj'
    bo.put("obj", o);
    BSONEncoder encoder = new BasicBSONEncoder();
    byte[] barr = encoder.encode(bo);
    ByteArrayInputStream bais = new ByteArrayInputStream(barr);
    ObjectMapper om = new ObjectMapper(new BsonFactory());
    om.registerModule(new BsonModule());
    T r = om.readValue(bais, cls);
    return r;
}

58. ElasticsearchSchemaFactory#create()

View license
@Override
public Schema create(SchemaPlus parentSchema, String name, Map<String, Object> operand) {
    final Map map = (Map) operand;
    final ObjectMapper mapper = new ObjectMapper();
    mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
    try {
        final Map<String, Integer> coordinates = mapper.readValue((String) map.get("coordinates"), new TypeReference<Map<String, Integer>>() {
        });
        final Map<String, String> userConfig = mapper.readValue((String) map.get("userConfig"), new TypeReference<Map<String, String>>() {
        });
        final String index = (String) map.get("index");
        return new ElasticsearchSchema(coordinates, userConfig, index);
    } catch (IOException e) {
        throw new RuntimeException("Cannot parse values from json", e);
    }
}

59. ArchivesJsonTest#test()

View license
@Test
public void test() throws Exception {
    final Archives archives = new Archives();
    archives.addItem().name("hello.jar").path("one/two/hello.jar");
    final ObjectMapper mapper = new ObjectMapper();
    JaxbAnnotationModule module = new JaxbAnnotationModule();
    // configure as necessary
    mapper.registerModule(module);
    mapper.writerWithDefaultPrettyPrinter().writeValue(System.out, archives);
}

60. PipelineOptionsTest#testCloneAs()

View license
@Test
public void testCloneAs() throws IOException {
    DerivedTestOptions options = PipelineOptionsFactory.create().as(DerivedTestOptions.class);
    options.setBaseValue(Lists.<Boolean>newArrayList());
    options.setIgnoredValue(Sets.<String>newHashSet());
    options.getIgnoredValue().add("ignoredString");
    options.setDerivedValue(0);
    BaseTestOptions clonedOptions = options.cloneAs(BaseTestOptions.class);
    assertNotSame(clonedOptions, options);
    assertNotSame(clonedOptions.getBaseValue(), options.getBaseValue());
    clonedOptions.getBaseValue().add(true);
    assertFalse(clonedOptions.getBaseValue().isEmpty());
    assertTrue(options.getBaseValue().isEmpty());
    assertNull(clonedOptions.getIgnoredValue());
    ObjectMapper mapper = new ObjectMapper();
    mapper.readValue(mapper.writeValueAsBytes(clonedOptions), PipelineOptions.class);
}

61. Metadata#writeFile()

Project: drill
Source File: Metadata.java
View license
/**
   * Serialize parquet metadata to json and write to a file
   *
   * @param parquetTableMetadata
   * @param p
   * @throws IOException
   */
private void writeFile(ParquetTableMetadata_v2 parquetTableMetadata, Path p) throws IOException {
    JsonFactory jsonFactory = new JsonFactory();
    jsonFactory.configure(Feature.AUTO_CLOSE_TARGET, false);
    jsonFactory.configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, false);
    ObjectMapper mapper = new ObjectMapper(jsonFactory);
    SimpleModule module = new SimpleModule();
    module.addSerializer(ColumnMetadata_v2.class, new ColumnMetadata_v2.Serializer());
    mapper.registerModule(module);
    FSDataOutputStream os = fs.create(p);
    mapper.writerWithDefaultPrettyPrinter().writeValue(os, parquetTableMetadata);
    os.flush();
    os.close();
}

62. HadoopDruidConverterConfigTest#simpleSerDe()

View license
@Test
public void simpleSerDe() throws IOException {
    final HadoopDruidConverterConfig config = new HadoopDruidConverterConfig("datasource", Interval.parse("2000/2010"), new IndexSpec(), ImmutableList.<DataSegment>of(), true, URI.create("file:/dev/null"), ImmutableMap.<String, String>of(), "HIGH", temporaryFolder.newFolder().getAbsolutePath());
    final ObjectMapper mapper = new DefaultObjectMapper();
    mapper.registerSubtypes(HadoopDruidConverterConfig.class);
    final byte[] value = mapper.writeValueAsBytes(config);
    final HadoopDruidConverterConfig config2 = mapper.readValue(value, HadoopDruidConverterConfig.class);
    Assert.assertEquals(mapper.writeValueAsString(config), mapper.writeValueAsString(config2));
}

63. JavaScriptExtractionFnTest#testSerde()

View license
@Test
public void testSerde() throws Exception {
    final ObjectMapper objectMapper = new DefaultObjectMapper();
    objectMapper.setInjectableValues(new InjectableValues.Std().addValue(JavaScriptConfig.class, JavaScriptConfig.getDefault()));
    final String json = "{ \"type\" : \"javascript\", \"function\" : \"function(str) { return str.substring(0,3); }\" }";
    JavaScriptExtractionFn extractionFn = (JavaScriptExtractionFn) objectMapper.readValue(json, ExtractionFn.class);
    Assert.assertEquals("function(str) { return str.substring(0,3); }", extractionFn.getFunction());
    // round trip
    Assert.assertEquals(extractionFn, objectMapper.readValue(objectMapper.writeValueAsBytes(extractionFn), ExtractionFn.class));
}

64. SegmentIdentifierTest#testSerde()

Project: druid
Source File: SegmentIdentifierTest.java
View license
@Test
public void testSerde() throws Exception {
    final ObjectMapper objectMapper = new DefaultObjectMapper();
    objectMapper.registerSubtypes(NumberedShardSpec.class);
    final SegmentIdentifier id2 = objectMapper.readValue(objectMapper.writeValueAsBytes(ID_1), SegmentIdentifier.class);
    Assert.assertEquals(ID_1, id2);
    Assert.assertEquals(DATA_SOURCE, id2.getDataSource());
    Assert.assertEquals(INTERVAL, id2.getInterval());
    Assert.assertEquals(VERSION, id2.getVersion());
    Assert.assertEquals(SHARD_SPEC_1.getPartitionNum(), id2.getShardSpec().getPartitionNum());
    Assert.assertEquals(SHARD_SPEC_1.getPartitions(), ((NumberedShardSpec) id2.getShardSpec()).getPartitions());
}

65. JsonTest#testRoundTrip()

Project: GeoIP2-java
Source File: JsonTest.java
View license
protected <T extends AbstractResponse> void testRoundTrip(Class<T> cls, String json) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(MapperFeature.CAN_OVERRIDE_ACCESS_MODIFIERS, false);
    InjectableValues inject = new InjectableValues.Std().addValue("locales", Collections.singletonList("en"));
    T response = mapper.reader(cls).with(inject).readValue(json);
    JsonNode expectedNode = mapper.readValue(json, JsonNode.class);
    JsonNode actualNode = mapper.readValue(response.toJson(), JsonNode.class);
    assertEquals(expectedNode, actualNode);
}

66. PrimaryModule#internalMapper()

Project: heroic
Source File: PrimaryModule.java
View license
@Provides
@Named(HeroicCore.APPLICATION_JSON_INTERNAL)
@PrimaryScope
ObjectMapper internalMapper(QueryParser parser, AggregationRegistry aggregation) {
    final ObjectMapper m = HeroicMappers.json(parser);
    /* configuration determined at runtime, unsuitable for testing */
    m.registerModule(aggregation.module());
    return m;
}

67. PipelineOptionsTest#testCloneAs()

View license
@Test
public void testCloneAs() throws IOException {
    DerivedTestOptions options = PipelineOptionsFactory.create().as(DerivedTestOptions.class);
    options.setBaseValue(Lists.<Boolean>newArrayList());
    options.setIgnoredValue(Sets.<String>newHashSet());
    options.getIgnoredValue().add("ignoredString");
    options.setDerivedValue(0);
    BaseTestOptions clonedOptions = options.cloneAs(BaseTestOptions.class);
    assertNotSame(clonedOptions, options);
    assertNotSame(clonedOptions.getBaseValue(), options.getBaseValue());
    clonedOptions.getBaseValue().add(true);
    assertFalse(clonedOptions.getBaseValue().isEmpty());
    assertTrue(options.getBaseValue().isEmpty());
    assertNull(clonedOptions.getIgnoredValue());
    ObjectMapper mapper = new ObjectMapper();
    mapper.readValue(mapper.writeValueAsBytes(clonedOptions), PipelineOptions.class);
}

68. MediaIT#shouldRoundTripQuotedPrintableFieldWithNoFieldVisibility()

Project: jsonschema2pojo
Source File: MediaIT.java
View license
@Test
public void shouldRoundTripQuotedPrintableFieldWithNoFieldVisibility() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setVisibilityChecker(mapper.getVisibilityChecker().withFieldVisibility(Visibility.NONE));
    roundTripAssertions(new ObjectMapper(), "anyBinaryEncoding", "\"=E3=82=A8=E3=83=B3=E3=82=B3=E3=83=BC=E3=83=89=E3=81=95=E3=82=8C=E3=81=9F=E6=96=87=E5=AD=97=E5=88=97\" is Japanese for \"encoded string\"", "\"???????????\" is Japanese for \"encoded string\"".getBytes("UTF-8"));
}

69. MetadataVersionRefresher#refresh()

Project: kylin
Source File: MetadataVersionRefresher.java
View license
public void refresh() throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
    List<String> all = Lists.newArrayList();
    collectFiles(this.store, "/", all);
    for (String path : all) {
        if (path.endsWith(MetadataConstants.FILE_SURFIX) && !(path.startsWith(ResourceStore.DICT_RESOURCE_ROOT) || path.startsWith(ResourceStore.SNAPSHOT_RESOURCE_ROOT))) {
            logger.info("Updating metadata version of path {}", path);
            ObjectNode objectNode = (ObjectNode) mapper.readTree(this.store.getResource(path).inputStream);
            objectNode.put("version", version);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            mapper.writeValue(baos, objectNode);
            ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
            this.store.putResource(path, bais, System.currentTimeMillis());
        }
    }
}

70. JacksonIssue429MyNamesTest#testStackTraceElementWithCustom()

View license
@Test
public void testStackTraceElementWithCustom() throws Exception {
    // first, via bean that contains StackTraceElement
    final StackTraceBean bean = MAPPER.readValue(aposToQuotes("{'Location':{'class':'package.SomeClass','method':'someMethod','file':'SomeClass.java','line':13}}"), 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 MyStackTraceElementDeserializer());
    mapper.registerModule(module);
    final StackTraceElement elem = mapper.readValue(aposToQuotes("{'class':'package.SomeClass','method':'someMethod','file':'SomeClass.java','line':13}"), StackTraceElement.class);
    Assert.assertNotNull(elem);
    Assert.assertEquals(StackTraceBean.NUM, elem.getLineNumber());
}

71. JacksonIssue429Test#testStackTraceElementWithCustom()

View license
@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());
}

72. StackTraceElementMixInTest#testFromJsonWithLog4jModule()

View license
@Test
public void testFromJsonWithLog4jModule() throws Exception {
    final ObjectMapper mapper = new ObjectMapper();
    final boolean encodeThreadContextAsList = false;
    final SimpleModule module = new Log4jJsonModule(encodeThreadContextAsList);
    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);
}

73. MessagePackDataformatForPojoTest#testSerializationWithoutSchema()

View license
@Test
public void testSerializationWithoutSchema() throws IOException {
    // to not affect shared objectMapper state
    ObjectMapper objectMapper = new ObjectMapper(factory);
    objectMapper.setAnnotationIntrospector(new JsonArrayFormat());
    byte[] bytes = objectMapper.writeValueAsBytes(complexPojo);
    String scheme = new String(bytes, Charset.forName("UTF-8"));
    // validating schema doesn't contains keys, that's just array
    assertThat(scheme, not(containsString("name")));
    ComplexPojo value = objectMapper.readValue(bytes, ComplexPojo.class);
    assertEquals("komamitsu", value.name);
    assertEquals(20, value.age);
    assertArrayEquals(complexPojo.values.toArray(), value.values.toArray());
    assertEquals(complexPojo.grades.get("math"), value.grades.get("math"));
}

74. MessagePackGeneratorTest#testDisableStr8Support()

View license
@Test
public void testDisableStr8Support() throws Exception {
    String str8LengthString = new String(new char[32]).replace("\0", "a");
    // Test that produced value having str8 format
    ObjectMapper defaultMapper = new ObjectMapper(new MessagePackFactory());
    byte[] resultWithStr8Format = defaultMapper.writeValueAsBytes(str8LengthString);
    assertEquals(resultWithStr8Format[0], MessagePack.Code.STR8);
    // Test that produced value does not having str8 format
    MessagePack.PackerConfig config = new MessagePack.PackerConfig().withStr8FormatSupport(false);
    ObjectMapper mapperWithConfig = new ObjectMapper(new MessagePackFactory(config));
    byte[] resultWithoutStr8Format = mapperWithConfig.writeValueAsBytes(str8LengthString);
    assertNotEquals(resultWithoutStr8Format[0], MessagePack.Code.STR8);
}

75. MessagePackGeneratorTest#testComplexTypeKey()

View license
@Test
public void testComplexTypeKey() throws IOException {
    HashMap<TinyPojo, Integer> map = new HashMap<TinyPojo, Integer>();
    TinyPojo pojo = new TinyPojo();
    pojo.t = "foo";
    map.put(pojo, 42);
    ObjectMapper objectMapper = new ObjectMapper(new MessagePackFactory());
    objectMapper.setSerializerFactory(new MessagePackSerializerFactory());
    byte[] bytes = objectMapper.writeValueAsBytes(map);
    MessageUnpacker unpacker = MessagePack.newDefaultUnpacker(bytes);
    assertThat(unpacker.unpackMapHeader(), is(1));
    assertThat(unpacker.unpackMapHeader(), is(1));
    assertThat(unpacker.unpackString(), is("t"));
    assertThat(unpacker.unpackString(), is("foo"));
    assertThat(unpacker.unpackInt(), is(42));
}

76. PathController#getPathsForProfile()

Project: odo
Source File: PathController.java
View license
@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);
}

77. PathController#testPath()

Project: odo
Source File: PathController.java
View license
@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);
}

78. BuckLibGenerator#main()

Project: onos
Source File: BuckLibGenerator.java
View license
/**
     * Main entry point.
     *
     * @param args command-line arguments; JSON input file and BUCK output file
     */
public static void main(String[] args) throws Exception {
    if (args.length < 2) {
        System.err.println("Not enough args.\n\nUSAGE: <json file> <output>");
        System.exit(5);
    }
    // Parse args
    String jsonFilePath = args[0];
    String outputBuckPath = args[1];
    // Load and parse input JSON file
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
    ObjectNode json = (ObjectNode) mapper.reader().readTree(new FileInputStream(jsonFilePath));
    // Traverse dependencies and build a dependency graph (DAG)
    BuckLibGenerator generator = new BuckLibGenerator(json).resolve();
    // Write the output BUCK file
    generator.write(outputBuckPath);
    System.out.printf("\nFinish writing %s\n", outputBuckPath);
}

79. ObjectMapperIT#testConstructor()

Project: pinpoint
Source File: ObjectMapperIT.java
View license
@Test
public void testConstructor() throws Exception {
    ObjectMapper mapper1 = new ObjectMapper();
    ObjectMapper mapper2 = new ObjectMapper(new JsonFactory());
    PluginTestVerifier verifier = PluginTestVerifierHolder.getInstance();
    verifier.printCache();
    Constructor<?> omConstructor = ObjectMapper.class.getConstructor(JsonFactory.class, DefaultSerializerProvider.class, DefaultDeserializationContext.class);
    Constructor<?> omConstructor1 = ObjectMapper.class.getConstructor();
    Constructor<?> omConstructor2 = ObjectMapper.class.getConstructor(JsonFactory.class);
    verifier.verifyTrace(event(SERVICE_TYPE, omConstructor));
    verifier.verifyTrace(event(SERVICE_TYPE, omConstructor1));
    verifier.verifyTrace(event(SERVICE_TYPE, omConstructor));
    verifier.verifyTrace(event(SERVICE_TYPE, omConstructor2));
    verifier.verifyTraceCount(0);
}

80. ConfiguredObjectJacksonModuleTest#testManageableAttributeType()

View license
public void testManageableAttributeType() throws IOException {
    ManagedAttributeValue testType = new TestManagedAttributeValue();
    ObjectMapper encoder = ConfiguredObjectJacksonModule.newObjectMapper();
    String encodedValue = encoder.writeValueAsString(testType);
    ObjectMapper decoder = new ObjectMapper();
    Map decodedMap = decoder.readValue(encodedValue, Map.class);
    assertEquals(3, decodedMap.size());
    assertTrue(decodedMap.containsKey("name"));
    assertTrue(decodedMap.containsKey("map"));
    assertTrue(decodedMap.containsKey("type"));
    assertEquals("foo", decodedMap.get("name"));
    assertEquals(Collections.singletonMap("key", "value"), decodedMap.get("map"));
    assertEquals(Collections.singletonMap("nested", true), decodedMap.get("type"));
}

81. EchoTestGwtServlet#doEchoRequest()

Project: resty-gwt
Source File: EchoTestGwtServlet.java
View license
@SuppressWarnings("unchecked")
private void doEchoRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
    Echo echo = new Echo();
    echo.path = request.getPathInfo();
    echo.params = new HashMap<String, String>();
    ObjectMapper mapper = new ObjectMapper();
    for (Map.Entry<String, String[]> entry : (Set<Map.Entry<String, String[]>>) request.getParameterMap().entrySet()) {
        if (entry.getValue().length == 1) {
            echo.params.put(entry.getKey(), entry.getValue()[0]);
        } else {
            echo.params.put(entry.getKey(), mapper.writeValueAsString(entry.getValue()));
        }
    }
    response.setContentType("application/json");
    mapper.writeValue(response.getOutputStream(), echo);
}

82. FunctionPhaseSerializerTest#init()

View license
@Before
public void init() throws IOException {
    this.out = new StringWriter();
    this.jg = new JsonFactory().createGenerator(out);
    ObjectMapper objectMapper = new ObjectMapper();
    SimpleModule specModule = new SimpleModule("SpecModule", Version.unknownVersion());
    specModule.addSerializer(PhaseFunction.class, new PhaseFunctionSerializer());
    specModule.addSerializer(FunctionPhase.class, new FunctionPhaseSerializer());
    objectMapper.registerModule(specModule);
    jg.setCodec(objectMapper);
}

83. InputSerializerTest#init()

View license
@Before
public void init() throws IOException {
    this.out = new StringWriter();
    this.jg = new JsonFactory().createGenerator(out);
    ObjectMapper objectMapper = new ObjectMapper();
    SimpleModule specModule = new SimpleModule("SpecModule", Version.unknownVersion());
    specModule.addSerializer(BucketInput.class, new BucketInputSerializer());
    specModule.addSerializer(SearchInput.class, new SearchInputSerializer());
    specModule.addSerializer(BucketKeyInput.class, new BucketKeyInputSerializer());
    specModule.addSerializer(IndexInput.class, new IndexInputSerializer());
    objectMapper.registerModule(specModule);
    jg.setCodec(objectMapper);
}

84. LinkPhaseSerializerTest#init()

View license
@Before
public void init() throws IOException {
    this.out = new StringWriter();
    this.jg = new JsonFactory().createGenerator(out);
    ObjectMapper objectMapper = new ObjectMapper();
    SimpleModule specModule = new SimpleModule("SpecModule", Version.unknownVersion());
    specModule.addSerializer(LinkPhase.class, new LinkPhaseSerializer());
    objectMapper.registerModule(specModule);
    jg.setCodec(objectMapper);
}

85. MapReduceSpecSerializerTest#init()

View license
@Before
public void init() throws IOException {
    this.out = new StringWriter();
    this.jg = new JsonFactory().createGenerator(out);
    ObjectMapper objectMapper = new ObjectMapper();
    SimpleModule specModule = new SimpleModule("SpecModule", Version.unknownVersion());
    specModule.addSerializer(PhaseFunction.class, new PhaseFunctionSerializer());
    specModule.addSerializer(LinkPhase.class, new LinkPhaseSerializer());
    specModule.addSerializer(FunctionPhase.class, new FunctionPhaseSerializer());
    specModule.addSerializer(BucketInput.class, new BucketInputSerializer());
    specModule.addSerializer(SearchInput.class, new SearchInputSerializer());
    specModule.addSerializer(BucketKeyInput.class, new BucketKeyInputSerializer());
    specModule.addSerializer(IndexInput.class, new IndexInputSerializer());
    objectMapper.registerModule(specModule);
    jg.setCodec(objectMapper);
}

86. PhaseFunctionSerializerTest#init()

View license
@Before
public void init() throws IOException {
    this.out = new StringWriter();
    this.jg = new JsonFactory().createGenerator(out);
    ObjectMapper objectMapper = new ObjectMapper();
    SimpleModule specModule = new SimpleModule("SpecModule", Version.unknownVersion());
    specModule.addSerializer(PhaseFunction.class, new PhaseFunctionSerializer());
    objectMapper.registerModule(specModule);
    jg.setCodec(objectMapper);
}

87. StrategyDeserializer#deserialize()

View license
@Override
public Strategy deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    ObjectMapper mapper = (ObjectMapper) jp.getCodec();
    ObjectNode root = mapper.readTree(jp);
    Class<? extends Strategy> theClass = null;
    Iterator<Map.Entry<String, JsonNode>> elementsIterator = root.fields();
    while (elementsIterator.hasNext()) {
        Map.Entry<String, JsonNode> element = elementsIterator.next();
        String name = element.getKey();
        Class<? extends Strategy> possibility = registry.get(name);
        if (possibility != null) {
            theClass = possibility;
        //                break;
        }
    }
    if (registry == null) {
        return null;
    }
    return mapper.treeToValue(root, theClass);
}

88. JsonObjectDeserializerTests#deserializeObjectShouldReadJson()

View license
@Test
public void deserializeObjectShouldReadJson() throws Exception {
    Deserializer deserializer = new NameAndAgeJsonComponent.Deserializer();
    SimpleModule module = new SimpleModule();
    module.addDeserializer(NameAndAge.class, deserializer);
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(module);
    NameAndAge nameAndAge = mapper.readValue("{\"name\":\"spring\",\"age\":100}", NameAndAge.class);
    assertThat(nameAndAge.getName()).isEqualTo("spring");
    assertThat(nameAndAge.getAge()).isEqualTo(100);
}

89. EndpointMBeanExporterTests#jsonMapConversionWithCustomObjectMapper()

View license
@Test
public void jsonMapConversionWithCustomObjectMapper() throws Exception {
    this.context = new GenericApplicationContext();
    ConstructorArgumentValues constructorArgs = new ConstructorArgumentValues();
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
    constructorArgs.addIndexedArgumentValue(0, objectMapper);
    this.context.registerBeanDefinition("endpointMbeanExporter", new RootBeanDefinition(EndpointMBeanExporter.class, constructorArgs, null));
    this.context.registerBeanDefinition("endpoint1", new RootBeanDefinition(JsonMapConversionEndpoint.class));
    this.context.refresh();
    MBeanExporter mbeanExporter = this.context.getBean(EndpointMBeanExporter.class);
    Object response = mbeanExporter.getServer().invoke(getObjectName("endpoint1", this.context), "getData", new Object[0], new String[0]);
    assertThat(response).isInstanceOf(Map.class);
    assertThat(((Map<?, ?>) response).get("date")).isInstanceOf(String.class);
}

90. MessageTagMapDeserializer#deserialize()

View license
@SuppressWarnings({ "unchecked", "deprecation" })
@Override
public Map<Integer, List<MessageTag>> deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new FacebookModule());
    jp.setCodec(mapper);
    if (jp.hasCurrentToken()) {
        JsonNode dataNode = jp.readValueAs(JsonNode.class);
        if (dataNode != null) {
            if (// OLD STYLE, SUPPORTED IN GRAPH API 2.3
            dataNode.getNodeType().equals(JsonNodeType.OBJECT)) {
                return (Map<Integer, List<MessageTag>>) mapper.reader(new TypeReference<Map<Integer, List<MessageTag>>>() {
                }).readValue(dataNode);
            } else if (// NEW STYLE 2.4/2.5-ish
            dataNode.getNodeType().equals(JsonNodeType.ARRAY)) {
                List<MessageTag> tagList = (List<MessageTag>) mapper.reader(new TypeReference<List<MessageTag>>() {
                }).readValue(dataNode);
                Map<Integer, List<MessageTag>> messageTagMap = new HashMap<Integer, List<MessageTag>>();
                for (MessageTag messageTag : tagList) {
                    messageTagMap.put(messageTag.getOffset(), Arrays.asList(messageTag));
                }
            }
        }
    }
    return Collections.emptyMap();
}

91. ReferenceListDeserializer#deserialize()

View license
@SuppressWarnings("unchecked")
@Override
public List<Reference> deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new FacebookModule());
    jp.setCodec(mapper);
    if (jp.hasCurrentToken()) {
        JsonNode dataNode = (JsonNode) jp.readValueAs(JsonNode.class).get("data");
        if (dataNode != null) {
            return (List<Reference>) mapper.reader(new TypeReference<List<Reference>>() {
            }).readValue(dataNode);
        }
    }
    return Collections.emptyList();
}

92. TagListDeserializer#deserialize()

View license
@SuppressWarnings("unchecked")
@Override
public List<Tag> deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new FacebookModule());
    jp.setCodec(mapper);
    if (jp.hasCurrentToken()) {
        JsonNode dataNode = (JsonNode) jp.readValueAs(JsonNode.class).get("data");
        return (List<Tag>) mapper.reader(new TypeReference<List<Tag>>() {
        }).readValue(dataNode);
    }
    return null;
}

93. CalendarTemplate_EventUrlTests#updateEvent()

View license
@Test
public void updateEvent() throws JsonParseException, JsonMappingException, IOException {
    ObjectMapper mapper = new ObjectMapper();
    // kind etc not used in Event.
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    Event event = mapper.readValue(jsonResource("mock_added_event").getFile(), Event.class);
    mockServer.expect(requestTo("https://www.googleapis.com/calendar/v3/calendars/primary/events/onn6d9kbhps6fc47m96auhtkdo?sendNotifications=true")).andExpect(method(PUT)).andExpect(// compatible with because ";charset=UTF-8" is included.
    content().contentTypeCompatibleWith(APPLICATION_JSON)).andRespond(withSuccess());
    google.calendarOperations().updateEvent("primary", event, true);
}

94. LikesListDeserializer#deserialize()

View license
@Override
public List<LinkedInProfile> deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new LinkedInModule());
    jp.setCodec(mapper);
    if (jp.hasCurrentToken()) {
        JsonNode dataNode = jp.readValueAs(JsonNode.class).get("values");
        List<LinkedInProfile> likes = new ArrayList<LinkedInProfile>();
        // Have to iterate through list due to person sub object.
        for (JsonNode like : dataNode) {
            LinkedInProfile profile = mapper.reader(new TypeReference<LinkedInProfile>() {
            }).readValue(like.get("person"));
            likes.add(profile);
        }
        return likes;
    }
    return null;
}

95. RecommendationsListDeserializer#deserialize()

View license
public List<Recommendation> deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new LinkedInModule());
    jp.setCodec(mapper);
    if (jp.hasCurrentToken()) {
        JsonNode dataNode = jp.readValueAs(JsonNode.class).get("values");
        if (dataNode != null) {
            return mapper.reader(new TypeReference<List<Recommendation>>() {
            }).readValue(dataNode);
        }
    }
    return null;
}

96. SimilarPlacesDeserializer#deserialize()

View license
@Override
public SimilarPlacesResponse deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new TwitterModule());
    jp.setCodec(mapper);
    JsonNode node = jp.readValueAs(JsonNode.class);
    JsonNode resultNode = node.get("result");
    String token = resultNode.get("token").textValue();
    JsonNode placesNode = resultNode.get("places");
    @SuppressWarnings("unchecked") List<Place> places = (List<Place>) mapper.reader(new TypeReference<List<Place>>() {
    }).readValue(placesNode);
    return new SimilarPlacesResponse(places, token);
}

97. DateFormatTest#serializeDateToLong()

Project: streamflow
Source File: DateFormatTest.java
View license
@Test
public void serializeDateToLong() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    SimpleModule serializerModule = new SimpleModule("SerializerModule", new Version(1, 0, 0, null));
    serializerModule.addSerializer(Date.class, new DateSerializer());
    mapper.registerModule(serializerModule);
    Date testDate = new Date();
    assertEquals("Serialized time should match Date.getTime()", Long.valueOf(testDate.getTime()), mapper.convertValue(testDate, Long.class));
}

98. DateFormatTest#deserializeLongToDate()

Project: streamflow
Source File: DateFormatTest.java
View license
@Test
public void deserializeLongToDate() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    SimpleModule deserializerModule = new SimpleModule("DeserializerModule", new Version(1, 0, 0, null));
    deserializerModule.addDeserializer(Date.class, new DateDeserializer());
    mapper.registerModule(deserializerModule);
    Date testDate = new Date();
    assertEquals("Deserialized time should match Date.getTime()", testDate, mapper.convertValue(testDate.getTime(), Date.class));
}

99. TestJackson#test()

Project: suro
Source File: TestJackson.java
View license
@Test
public void test() throws IOException {
    String spec = "{\"a\":\"aaa\", \"b\":\"bbb\"}";
    ObjectMapper mapper = new DefaultObjectMapper();
    final Map<String, Object> injectables = Maps.newHashMap();
    injectables.put("test", "test");
    injectables.put("b", "binjected");
    mapper.setInjectableValues(new InjectableValues() {

        @Override
        public Object findInjectableValue(Object valueId, DeserializationContext ctxt, BeanProperty forProperty, Object beanInstance) {
            return injectables.get(valueId);
        }
    });
    TestClass test = mapper.readValue(spec, new TypeReference<TestClass>() {
    });
    assertEquals(test.getTest(), "test");
    assertEquals(test.getB(), "bbb");
}

100. JSONTest#map()

Project: syncope
Source File: JSONTest.java
View license
@Test
public void map() throws IOException {
    WorkflowFormPropertyTO prop = new WorkflowFormPropertyTO();
    prop.getEnumValues().put("key1", "value1");
    prop.getEnumValues().put("key2", "value2");
    ObjectMapper mapper = new ObjectMapper();
    StringWriter writer = new StringWriter();
    mapper.writeValue(writer, prop);
    WorkflowFormPropertyTO unserializedProp = mapper.readValue(writer.toString(), WorkflowFormPropertyTO.class);
    assertEquals(prop, unserializedProp);
}