使用jackson-datatype-jsr310在Spring配置中进行RESTful服务

时间:2016-07-12 13:18:52

标签: java json spring jackson

我正在尝试配置Java 8& Spring 4.3.1 app使用RESTful服务。我让它与下面的配置完美配合,直到我引入 ContextResolver

ContextResolver的原因是因为我需要将java.time.LocalDateTime格式化为 JSON

我首先尝试在我的模型bean上使用注释添加 @JsonFormat

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = DATE_FORMAT)    
@DateTimeFormat(pattern=DATE_FORMAT) 
@Column(name = "JOINING_DATE", nullable = false)
@Type(type="org.hibernate.type.LocalDateTimeType")
private LocalDateTime joiningDate;

并得到以下错误

  

java.lang.NoSuchMethodError:   com.fasterxml.jackson.datatype.jsr310.ser.JSR310FormattedSerializerBase.findFormatOverrides(LCOM / fasterxml /杰克逊/数据绑定/ SerializerProvider; LCOM / fasterxml /杰克逊/数据绑定/的BeanProperty; Ljava /郎/类;)LCOM / fasterxml /杰克逊/注释/ JsonFormat $值;

其次,我删除了@JsonFormat注释并尝试使用 ContextResolver

ObjectMapperContextResolver.java

package com.jobs.spring.configuration;

import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;

@Provider
public class ObjectMapperContextResolver implements ContextResolver<ObjectMapper> {  
    private final ObjectMapper MAPPER;

    public ObjectMapperContextResolver() {
        MAPPER = new ObjectMapper();
        MAPPER.registerModule(new JavaTimeModule());
        MAPPER.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    }

    @Override
    public ObjectMapper getContext(Class<?> type) {
        return MAPPER;
    }  
}

并得到以下错误

  

[org.springframework.web.servlet.PageNotFound](默认任务-4)否   使用URI找到HTTP请求的映射[/ jbosswildfly / employee / list]   在DispatcherServlet中,名称为&#39; rest&#39;

请有人建议,我认为我的Spring配置可能不正确。

  • 在第一种情况下,使用 @JsonFormat注释,请求 点击RESTful服务,但得到 NoSuchMethodError 建议 我的依赖关系不正确。
  • 第二种情况,使用 ContextResolver ,请求**没有 找到DispatcherServelet **(因此无法访问RESTful 服务)。这表明我的Spring配置不正确。

正如我所说,如果我不使用@JsonFormat注释或ContextResolver,我可以成功调用RESTful服务(但我需要格式化日期)。

谢谢

我的配置如下:

的pom.xml

.
.
.
<jackson.version>2.8.0</jackson.version>
.
.
.
        <!-- JSON -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>${jackson.version}</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.datatype</groupId>
            <artifactId>jackson-datatype-jsr310</artifactId>
            <version>${jackson.version}</version>
        </dependency>

的web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app version="3.1"
         xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         metadata-complete="false">

         <servlet>
            <servlet-name>rest</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <load-on-startup>1</load-on-startup>
         </servlet>

         <servlet-mapping>
            <servlet-name>rest</servlet-name>
            <url-pattern>/*</url-pattern>
         </servlet-mapping>

</web-app>

其余-servlet.xml中

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
                           http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
                           http://www.springframework.org/schema/context 
                           http://www.springframework.org/schema/context/spring-context-4.0.xsd
                           http://www.springframework.org/schema/mvc 
                           http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

    <context:component-scan base-package="com.jobs.spring" />
    <mvc:annotation-driven />    
</beans>

休息控制器

@CrossOrigin(origins = {"*"})
@RestController
@RequestMapping(EmployeeRESTService.BASE_URI)
public class EmployeeRESTService {

    public static final String BASE_URI = "/employee";

    @Autowired
    private EmployeeService employeeService;

    @RequestMapping(value = "/list", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    public List<Employee> findAllEmployees() {
        return employeeService.findAll();
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
    public @ResponseBody String saveEmployee(@RequestBody Employee employee){
        Long id = employeeService.save(employee);
        return Long.toString(id);
    }
}

1 个答案:

答案 0 :(得分:2)

<强>解决

通过添加以下类,它现在可以使用:

package com.jobs.spring.configuration;

import java.text.SimpleDateFormat;
import java.util.List;

import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.converter.xml.MappingJackson2XmlHttpMessageConverter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
@EnableWebMvc
public class WebConfiguration extends WebMvcConfigurerAdapter {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
        builder.indentOutput(true).dateFormat(new SimpleDateFormat("yyyy-MM-dd"));
        converters.add(new MappingJackson2HttpMessageConverter(builder.build()));
        converters.add(new MappingJackson2XmlHttpMessageConverter(builder.createXmlMapper(true).build()));
    }
}