Search in sources :

Example 36 with JavaType

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

the class AbstractJackson2HttpMessageConverter method writeInternal.

@Override
protected void writeInternal(Object object, Type type, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException {
    MediaType contentType = outputMessage.getHeaders().getContentType();
    JsonEncoding encoding = getJsonEncoding(contentType);
    JsonGenerator generator = this.objectMapper.getFactory().createGenerator(outputMessage.getBody(), encoding);
    try {
        writePrefix(generator, object);
        Class<?> serializationView = null;
        FilterProvider filters = null;
        Object value = object;
        JavaType javaType = null;
        if (object instanceof MappingJacksonValue) {
            MappingJacksonValue container = (MappingJacksonValue) object;
            value = container.getValue();
            serializationView = container.getSerializationView();
            filters = container.getFilters();
        }
        if (type != null && value != null && TypeUtils.isAssignable(type, value.getClass())) {
            javaType = getJavaType(type, null);
        }
        ObjectWriter objectWriter;
        if (serializationView != null) {
            objectWriter = this.objectMapper.writerWithView(serializationView);
        } else if (filters != null) {
            objectWriter = this.objectMapper.writer(filters);
        } else {
            objectWriter = this.objectMapper.writer();
        }
        if (javaType != null && javaType.isContainerType()) {
            objectWriter = objectWriter.forType(javaType);
        }
        SerializationConfig config = objectWriter.getConfig();
        if (contentType != null && contentType.isCompatibleWith(MediaType.TEXT_EVENT_STREAM) && config.isEnabled(SerializationFeature.INDENT_OUTPUT)) {
            objectWriter = objectWriter.with(this.ssePrettyPrinter);
        }
        objectWriter.writeValue(generator, value);
        writeSuffix(generator, object);
        generator.flush();
    } catch (JsonProcessingException ex) {
        throw new HttpMessageNotWritableException("Could not write content: " + ex.getMessage(), ex);
    }
}
Also used : JavaType(com.fasterxml.jackson.databind.JavaType) HttpMessageNotWritableException(org.springframework.http.converter.HttpMessageNotWritableException) JsonEncoding(com.fasterxml.jackson.core.JsonEncoding) SerializationConfig(com.fasterxml.jackson.databind.SerializationConfig) MediaType(org.springframework.http.MediaType) JsonGenerator(com.fasterxml.jackson.core.JsonGenerator) ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) FilterProvider(com.fasterxml.jackson.databind.ser.FilterProvider)

Example 37 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 38 with JavaType

use of com.fasterxml.jackson.databind.JavaType in project torodb by torodb.

the class DescriptionFactoryWrapper method expectArrayFormat.

@Override
public JsonArrayFormatVisitor expectArrayFormat(JavaType convertedType) {
    final JsonPointer jsonPointer = getJsonPointer();
    return new JsonArrayFormatVisitor.Base(getProvider()) {

        @Override
        public void itemsFormat(JsonFormatVisitable handler, JavaType elementType) throws JsonMappingException {
            SerializerProvider p = getProvider();
            JsonSerializer<Object> s = p.findValueSerializer(elementType);
            s.acceptJsonFormatVisitor(new DescriptionFactoryWrapper(DescriptionFactoryWrapper.this, jsonPointer.append(JsonPointer.valueOf("/<index>")), p), elementType);
        }
    };
}
Also used : JsonFormatVisitable(com.fasterxml.jackson.databind.jsonFormatVisitors.JsonFormatVisitable) JavaType(com.fasterxml.jackson.databind.JavaType) JsonPointer(com.fasterxml.jackson.core.JsonPointer) SerializerProvider(com.fasterxml.jackson.databind.SerializerProvider)

Example 39 with JavaType

use of com.fasterxml.jackson.databind.JavaType in project torodb by torodb.

the class DescriptionFactoryWrapper method document.

private void document(JsonPointer propPointer, BeanProperty prop) {
    JavaType type = prop.getType();
    if (hasDescription(prop) && !isPrimitive(type) && !type.isEnumType() && !type.isMapLikeType()) {
        console.println("");
    } else if (isPrimitive(type) || type.isEnumType()) {
        printTabs();
        console.print(propPointer.toString());
        console.print("=");
    } else if (type.isMapLikeType()) {
        printTabs();
        console.print(propPointer.append(JsonPointer.compile("/<string>")).toString());
        console.print("=");
        type = type.getContentType();
    }
    if (isPrimitive(type)) {
        console.print("<");
        console.print(CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_CAMEL, type.getRawClass().getSimpleName()));
        console.print(">");
    } else if (type.isEnumType()) {
        console.print("<enum:string>");
    }
    if (hasDescription(prop) && !isPrimitive(type) && !type.isEnumType()) {
        printTabs();
    }
    printDescription(prop);
    if (hasDescription(prop) || isPrimitive(type) || type.isEnumType()) {
        console.println("");
    }
    if (hasDescription(prop) && !isPrimitive(type) && !type.isEnumType()) {
        console.println("");
    }
    if (type.isEnumType()) {
        for (Field enumField : type.getRawClass().getDeclaredFields()) {
            if (!enumField.isEnumConstant()) {
                continue;
            }
            printTabs();
            console.print(" - ");
            console.print(enumField.getName());
            Description enumConstantConfigProperty = enumField.getAnnotation(Description.class);
            if (enumConstantConfigProperty != null && enumConstantConfigProperty.value() != null) {
                console.print(" # ");
                console.print(resourceBundle.getString(enumConstantConfigProperty.value()));
            }
            console.println("");
        }
    }
}
Also used : Field(java.lang.reflect.Field) JavaType(com.fasterxml.jackson.databind.JavaType) Description(com.torodb.packaging.config.annotation.Description)

Example 40 with JavaType

use of com.fasterxml.jackson.databind.JavaType in project torodb by torodb.

the class AbstractBackendSerializer method acceptJsonFormatVisitor.

@Override
public void acceptJsonFormatVisitor(JsonFormatVisitorWrapper visitor, JavaType type) throws JsonMappingException {
    if (visitor == null) {
        return;
    }
    JsonObjectFormatVisitor v = visitor.expectObjectFormat(type);
    SerializerProvider prov = visitor.getProvider();
    final SerializationConfig config = prov.getConfig();
    BeanDescription beanDesc = config.introspect(type);
    JsonSubTypes jsonSubTypes;
    if (v != null) {
        for (BeanPropertyDefinition propDef : beanDesc.findProperties()) {
            if (propDef.isExplicitlyIncluded()) {
                jsonSubTypes = propDef.getPrimaryMember().getAnnotation(JsonSubTypes.class);
                if (jsonSubTypes != null) {
                    for (JsonSubTypes.Type jsonSubType : jsonSubTypes.value()) {
                        JavaType subType = TypeFactory.defaultInstance().constructType(jsonSubType.value());
                        depositSchemaProperty(v, jsonSubType.name(), subType);
                    }
                } else {
                    depositSchemaProperty(v, propDef.getName(), propDef.getPrimaryMember().getType(beanDesc.bindingsForBeanType()));
                }
            }
        }
    }
}
Also used : JsonSubTypes(com.fasterxml.jackson.annotation.JsonSubTypes) JavaType(com.fasterxml.jackson.databind.JavaType) JsonObjectFormatVisitor(com.fasterxml.jackson.databind.jsonFormatVisitors.JsonObjectFormatVisitor) SerializationConfig(com.fasterxml.jackson.databind.SerializationConfig) BeanDescription(com.fasterxml.jackson.databind.BeanDescription) BeanPropertyDefinition(com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition) SerializerProvider(com.fasterxml.jackson.databind.SerializerProvider)

Aggregations

JavaType (com.fasterxml.jackson.databind.JavaType)264 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)31 Test (org.junit.Test)27 IOException (java.io.IOException)21 BeanDescription (com.fasterxml.jackson.databind.BeanDescription)20 BeanPropertyDefinition (com.fasterxml.jackson.databind.introspect.BeanPropertyDefinition)17 ArrayList (java.util.ArrayList)17 TypeFactory (com.fasterxml.jackson.databind.type.TypeFactory)15 Property (io.swagger.models.properties.Property)15 List (java.util.List)15 Map (java.util.Map)13 StringProperty (io.swagger.models.properties.StringProperty)12 ObjectWriter (com.fasterxml.jackson.databind.ObjectWriter)10 ModelImpl (io.swagger.models.ModelImpl)10 MapProperty (io.swagger.models.properties.MapProperty)10 Method (java.lang.reflect.Method)10 Type (java.lang.reflect.Type)10 JsonDeserializer (com.fasterxml.jackson.databind.JsonDeserializer)9 ArrayProperty (io.swagger.models.properties.ArrayProperty)9 IntegerProperty (io.swagger.models.properties.IntegerProperty)9