Spring MVC 3.2 Rest JSON数据转换

时间:2014-07-15 18:46:22

标签: java json spring rest spring-mvc

我正在尝试从我的Spring Controller发送数据列表作为JSON,但它正在抛出"无法找到可接受的表示"。下面是我的应用程序各个部分的代码片段。

的pom.xml

<hibernate.version>4.1.4.Final</hibernate.version>
<spring.version>3.2.3.RELEASE</spring.version>
<spring.data.version>1.3.2.RELEASE</spring.data.version>
<jackson.version>1.9.12</jackson.version>
<spring.security.version>3.2.2.RELEASE</spring.security.version>

<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>${jackson.version}</version>
</dependency>
<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-core-asl</artifactId>
    <version>${jackson.version}</version>
</dependency>

<!-- 
<dependency>
   <groupId>com.fasterxml.jackson.core</groupId>
   <artifactId>jackson-core</artifactId>
   <version>2.1.0</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.1.0</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.1.0</version>
</dependency>
 -->

WebConfig。我尝试了各种博客和stackoverflow中提到的所有可能的方法。我也试过了那些评论过的。

@Configuration
@EnableWebMvc
@EnableTransactionManagement
@ComponentScan("com.test.testing")
//@PropertySource("classpath:application.properties")
@EnableJpaRepositories("com.test.testing.config.dao")
public class WebAppConfig extends WebMvcConfigurerAdapter {

    @Resource
    private Environment env;

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/login").setViewName("login");
        registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
    }




    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        configurer.favorPathExtension(true)
        .useJaf(false)
        .ignoreAcceptHeader(true)
        .mediaType("html", MediaType.TEXT_HTML)
        .mediaType("json", MediaType.APPLICATION_JSON)
        .mediaType("plain", MediaType.TEXT_PLAIN)
        .defaultContentType(MediaType.TEXT_HTML);
    }

    @Bean
    public ViewResolver contentNegotiatingViewResolver(
            ContentNegotiationManager manager) {

        List<ViewResolver> resolvers = new ArrayList<ViewResolver>();

        InternalResourceViewResolver r1 = new InternalResourceViewResolver();
        r1.setPrefix("/WEB-INF/pages/");
        r1.setSuffix(".jsp");
        r1.setViewClass(JstlView.class);
        resolvers.add(r1);

        JsonViewResolver r2 = new JsonViewResolver();

        resolvers.add(r2);

        ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
        resolver.setViewResolvers(resolvers);
        resolver.setContentNegotiationManager(manager);
        return resolver;

    }



    /**
     * View resolver for returning JSON in a view-based system. Always returns a
     * {@link MappingJacksonJsonView}.
     */
    public class JsonViewResolver implements ViewResolver {
        @Override
        public View resolveViewName(String viewName, Locale locale)
                throws Exception {
            MappingJacksonJsonView view = new MappingJacksonJsonView();
            view.setPrettyPrint(true);
            return view;
        }
    }

    @Bean
    public HandlerExceptionResolver handlerExceptionResolver() {
        SimpleMappingExceptionResolver exceptionResolver = new SimpleMappingExceptionResolver();
        exceptionResolver.setDefaultErrorView("uncaughtException");
        Properties mappings = new Properties();
        mappings.put(".DataAccessException", "dataAccessFailure");
        mappings.put(".NoSuchRequestHandlingMethodException", "resourceNotFound");
        mappings.put(".TypeMismatchException", "resourceNotFound");
        mappings.put(".MissingServletRequestParameterException", "resourceNotFound");
        exceptionResolver.setExceptionMappings(mappings );
        return exceptionResolver;
    }




    /* (non-Javadoc)
     * @see org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter#configureMessageConverters(java.util.List)
     */

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {

        converters.add(new org.springframework.http.converter.StringHttpMessageConverter());
        //converters.add(new org.springframework.http.converter.json.MappingJacksonHttpMessageConverter());
        //converters.add(new org.springframework.http.converter.json.MappingJackson2HttpMessageConverter());

        /*
        org.springframework.http.converter.json.MappingJackson2HttpMessageConverter mappingJacksonHttpMessageConverter = new org.springframework.http.converter.json.MappingJackson2HttpMessageConverter();
        mappingJacksonHttpMessageConverter.setObjectMapper(new com.test.testing.objectmapper.MasterDataObjectMapper());

        converters.add(mappingJacksonHttpMessageConverter);

        */

        org.springframework.http.converter.json.MappingJacksonHttpMessageConverter mappingJacksonHttpMessageConverter = new MappingJacksonHttpMessageConverter();
        mappingJacksonHttpMessageConverter.setObjectMapper(new MasterDataObjectMapper());
        converters.add(mappingJacksonHttpMessageConverter);

        super.configureMessageConverters(converters);


    }


}

控制器。控制器方法的Sysout

getMasterTypeData主数据类型列表:[MasterType [id = 1,value = UAT / QA],MasterType [id = 4,value = Development],MasterType [id = 2,value = Model],MasterType [id = 3 ,价值=生产]]

@RequestMapping(value = "/getdata/{type}", method = RequestMethod.GET,produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public List<MasterType> getMasterTypeData(@PathVariable String type) {

        MASTERDATATYPE master = MASTERDATATYPE.getMasterDataType(type); 
        List<MasterType> masterdatTypeList = new ArrayList<MasterType>();
        System.out.println("getMasterTypeData Input :"+type+",MASTERDATATYPE :"+master);

        // some logics to populate masterdatTypeList 

        System.out.println("getMasterTypeData Master Data Type List :"+masterdatTypeList);
        return masterdatTypeList;
    }

最后我想将MasterType类发送回浏览器广告JSON对象

@JsonAutoDetect
public class MasterType implements Serializable {

/**
 * 
 */
private static final long serialVersionUID = 1L;

private Long id;
private String value;

public MasterType() {
    // TODO Auto-generated constructor stub
}

public MasterType(EnvironmentType environmentType){
    this.id = environmentType.getId();
    this.value = environmentType.getEnvName();
}

public MasterType(OperatingSystemType operatingSystemType){
    this.id = operatingSystemType.getId();
    this.value = operatingSystemType.getOsName();
}

public MasterType(ServerStorageBillableType serverStorageBillableType){
    this.id = serverStorageBillableType.getId();
    this.value = serverStorageBillableType.getStorageBillableTypeDesc();
}

public MasterType(ServerStorageStatusType serverStorageStatusType){
    this.id = serverStorageStatusType.getId();
    this.value = serverStorageStatusType.getStorageStatusName();
}

public MasterType(ServerStorageType serverStorageType){
    this.id = serverStorageType.getId();
    this.value = serverStorageType.getStorageTypeName();
}

public MasterType(ServerComponentType serverComponentType){
    this.id = serverComponentType.getId();
    this.value = serverComponentType.getComponentName();
}

/**
 * @return the id
 */
//@JsonProperty
public Long getId() {
    return id;
}

/**
 * @param id the id to set
 */
public void setId(Long id) {
    this.id = id;
}

/**
 * @return the value
 */
//@JsonProperty
public String getValue() {
    return value;
}
/**
 * @param value the value to set
 */
public void setValue(String value) {
    this.value = value;
}
/* (non-Javadoc)
 * @see java.lang.Object#hashCode()
 */
@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + (int) (id ^ (id >>> 32));
    result = prime * result + ((value == null) ? 0 : value.hashCode());
    return result;
}
/* (non-Javadoc)
 * @see java.lang.Object#equals(java.lang.Object)
 */
@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    MasterType other = (MasterType) obj;
    if (id != other.id)
        return false;
    if (value == null) {
        if (other.value != null)
            return false;
    } else if (!value.equals(other.value))
        return false;
    return true;
}
/* (non-Javadoc)
 * @see java.lang.Object#toString()
 */
@Override
public String toString() {
    StringBuilder builder = new StringBuilder();
    builder.append("MasterType [id=").append(id).append(", value=")
            .append(value).append("]");
    return builder.toString();
}

}

你能帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

检查您的请求标头是否已设置并且具有“Accept application / json”,您可以使用firebug检查请求标头。