Search in sources :

Example 46 with JavaType

use of com.fasterxml.jackson.databind.JavaType in project spring-framework by spring-projects.

the class MappingJackson2HttpMessageConverterTests method readGenerics.

@Test
@SuppressWarnings("unchecked")
public void readGenerics() throws IOException {
    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter() {

        @Override
        protected JavaType getJavaType(Type type, Class<?> contextClass) {
            if (type instanceof Class && List.class.isAssignableFrom((Class<?>) type)) {
                return new ObjectMapper().getTypeFactory().constructCollectionType(ArrayList.class, MyBean.class);
            } else {
                return super.getJavaType(type, contextClass);
            }
        }
    };
    String body = "[{\"bytes\":\"AQI=\",\"array\":[\"Foo\",\"Bar\"],\"number\":42,\"string\":\"Foo\",\"bool\":true,\"fraction\":42.0}]";
    MockHttpInputMessage inputMessage = new MockHttpInputMessage(body.getBytes("UTF-8"));
    inputMessage.getHeaders().setContentType(new MediaType("application", "json"));
    List<MyBean> results = (List<MyBean>) converter.read(List.class, inputMessage);
    assertEquals(1, results.size());
    MyBean result = results.get(0);
    assertEquals("Foo", result.getString());
    assertEquals(42, result.getNumber());
    assertEquals(42F, result.getFraction(), 0F);
    assertArrayEquals(new String[] { "Foo", "Bar" }, result.getArray());
    assertTrue(result.isBool());
    assertArrayEquals(new byte[] { 0x1, 0x2 }, result.getBytes());
}
Also used : MediaType(org.springframework.http.MediaType) Type(java.lang.reflect.Type) JavaType(com.fasterxml.jackson.databind.JavaType) MockHttpInputMessage(org.springframework.http.MockHttpInputMessage) MediaType(org.springframework.http.MediaType) ArrayList(java.util.ArrayList) List(java.util.List) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Test(org.junit.Test)

Example 47 with JavaType

use of com.fasterxml.jackson.databind.JavaType in project leopard by tanhaichao.

the class UnderlineJson method toEnumListByOnlyKey.

@SuppressWarnings({ "unchecked", "rawtypes" })
private static <T> List<T> toEnumListByOnlyKey(String json, Class<T> clazz) {
    JavaType javaType = getObjectMapper().getTypeFactory().constructParametrizedType(ArrayList.class, List.class, Object.class);
    List<Object> keyList;
    try {
        keyList = getObjectMapper().readValue(json, javaType);
    } catch (Exception e) {
        logger.error("clazz:" + clazz.getName() + " json:" + json);
        throw new JsonException(e.getMessage(), e);
    }
    // System.err.println("keyList:" + keyList);
    List<T> list = new ArrayList<T>();
    for (Object key : keyList) {
        T onum = (T) EnumUtil.toEnum(key, (Class<Enum>) clazz);
        // System.err.println("key:" + key + " onum:" + onum);
        list.add(onum);
    }
    return list;
}
Also used : JsonException(io.leopard.json.JsonException) JavaType(com.fasterxml.jackson.databind.JavaType) ArrayList(java.util.ArrayList) EnumConstantInvalidException(io.leopard.lang.inum.EnumConstantInvalidException) JsonException(io.leopard.json.JsonException)

Example 48 with JavaType

use of com.fasterxml.jackson.databind.JavaType in project EnrichmentMapApp by BaderLab.

the class PropertiesJsonDeserializer method readValue.

public static Object readValue(final String key, final String input, final ObjectMapper mapper, final AbstractChart<?> chart) {
    Object value = null;
    final Class<?> type = chart.getSettingType(key);
    if (type != null) {
        final TypeFactory typeFactory = mapper.getTypeFactory();
        try {
            if (type == Array.class) {
                final Class<?> elementType = chart.getSettingElementType(key);
                if (elementType != null) {
                    final ArrayType arrType = typeFactory.constructArrayType(elementType);
                    if (mapper.canDeserialize(arrType))
                        value = mapper.readValue(input, arrType);
                }
            } else if (List.class.isAssignableFrom(type)) {
                final Class<?> elementType = chart.getSettingElementType(key);
                if (elementType != null) {
                    final CollectionType collType = typeFactory.constructCollectionType(List.class, elementType);
                    if (mapper.canDeserialize(collType))
                        value = mapper.readValue(input, collType);
                }
            } else {
                final JavaType simpleType = typeFactory.constructSimpleType(type, new JavaType[] {});
                if (mapper.canDeserialize(simpleType))
                    value = mapper.readValue(input, simpleType);
            }
        } catch (Exception e) {
            logger.error("Cannot parse JSON field " + key, e);
        }
    }
    return value;
}
Also used : ArrayType(com.fasterxml.jackson.databind.type.ArrayType) JavaType(com.fasterxml.jackson.databind.JavaType) CollectionType(com.fasterxml.jackson.databind.type.CollectionType) List(java.util.List) TypeFactory(com.fasterxml.jackson.databind.type.TypeFactory) IOException(java.io.IOException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Example 49 with JavaType

use of com.fasterxml.jackson.databind.JavaType in project druid by druid-io.

the class AggregationTestHelper method makeStringSerdeQueryRunner.

public QueryRunner<Row> makeStringSerdeQueryRunner(final ObjectMapper mapper, final QueryToolChest toolChest, final Query<Row> query, final QueryRunner<Row> baseRunner) {
    return new QueryRunner<Row>() {

        @Override
        public Sequence<Row> run(Query<Row> query, Map<String, Object> map) {
            try {
                Sequence<Row> resultSeq = baseRunner.run(query, Maps.<String, Object>newHashMap());
                final Yielder yielder = resultSeq.toYielder(null, new YieldingAccumulator() {

                    @Override
                    public Object accumulate(Object accumulated, Object in) {
                        yield();
                        return in;
                    }
                });
                String resultStr = mapper.writer().writeValueAsString(yielder);
                TypeFactory typeFactory = mapper.getTypeFactory();
                JavaType baseType = typeFactory.constructType(toolChest.getResultTypeReference());
                List resultRows = Lists.transform(readQueryResultArrayFromString(resultStr), toolChest.makePreComputeManipulatorFn(query, MetricManipulatorFns.deserializing()));
                return Sequences.simple(resultRows);
            } catch (Exception ex) {
                throw Throwables.propagate(ex);
            }
        }
    };
}
Also used : Yielder(io.druid.java.util.common.guava.Yielder) Query(io.druid.query.Query) YieldingAccumulator(io.druid.java.util.common.guava.YieldingAccumulator) FinalizeResultsQueryRunner(io.druid.query.FinalizeResultsQueryRunner) QueryRunner(io.druid.query.QueryRunner) IOException(java.io.IOException) JavaType(com.fasterxml.jackson.databind.JavaType) List(java.util.List) ArrayList(java.util.ArrayList) Row(io.druid.data.input.Row) TypeFactory(com.fasterxml.jackson.databind.type.TypeFactory) Map(java.util.Map)

Example 50 with JavaType

use of com.fasterxml.jackson.databind.JavaType in project jvm-serializers by eishay.

the class JacksonAvroDatabind method register.

public static void register(TestGroups groups) {
    ObjectMapper mapper = new ObjectMapper(new AvroFactory());
    mapper.enable(SerializationFeature.WRITE_ENUMS_USING_INDEX);
    JavaType type = mapper.constructType(MediaContent.class);
    AvroSchema schema = new AvroSchema(Avro.Media.sMediaContent);
    ObjectReader reader = mapper.readerFor(type).with(schema);
    ObjectWriter writer = mapper.writerFor(type).with(schema);
    groups.media.add(JavaBuiltIn.mediaTransformer, new StdJacksonDataBind<MediaContent>("avro/jackson/databind", type, mapper, reader, writer), new SerFeatures(SerFormat.JSON, SerGraph.FLAT_TREE, SerClass.ZERO_KNOWLEDGE, ""));
}
Also used : JavaType(com.fasterxml.jackson.databind.JavaType) AvroFactory(com.fasterxml.jackson.dataformat.avro.AvroFactory) AvroSchema(com.fasterxml.jackson.dataformat.avro.AvroSchema) ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) MediaContent(data.media.MediaContent) ObjectReader(com.fasterxml.jackson.databind.ObjectReader) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Aggregations

JavaType (com.fasterxml.jackson.databind.JavaType)110 TypeFactory (com.fasterxml.jackson.databind.type.TypeFactory)10 IOException (java.io.IOException)10 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)7 ObjectWriter (com.fasterxml.jackson.databind.ObjectWriter)7 ArrayList (java.util.ArrayList)7 BeanDescription (com.fasterxml.jackson.databind.BeanDescription)6 Property (io.swagger.models.properties.Property)6 Test (org.junit.Test)6 ObjectReader (com.fasterxml.jackson.databind.ObjectReader)5 Method (java.lang.reflect.Method)5 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)4 StringProperty (io.swagger.models.properties.StringProperty)4 List (java.util.List)4 JsonGenerator (com.fasterxml.jackson.core.JsonGenerator)3 NamedType (com.fasterxml.jackson.databind.jsontype.NamedType)3 CollectionType (com.fasterxml.jackson.databind.type.CollectionType)3 MapType (com.fasterxml.jackson.databind.type.MapType)3 ClassConfig (io.servicecomb.common.javassist.ClassConfig)3 ModelImpl (io.swagger.models.ModelImpl)3