postForEntity不会产生正确的JSON表示......在我的智慧结束时

时间:2014-09-06 15:04:02

标签: java json spring rest spring-mvc

我是Spring MVC REST的新手。我花了几个小时谷歌搜索并尝试不同的方法来解决这个问题。 为什么这段代码不会产生带双引号的JSON ???

            List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();            
        MappingJackson2HttpMessageConverter mappingJacksonHttpMessageConverter = new MappingJackson2HttpMessageConverter();
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
        mappingJacksonHttpMessageConverter.setObjectMapper(objectMapper);
        mappingJacksonHttpMessageConverter.setPrettyPrint(true);                    
        converters.add(mappingJacksonHttpMessageConverter);             
        template.setMessageConverters(converters);

        ResponseEntity<EAApplication> response = template.postForEntity(
            LOCAL_URI,
            requestEntity, EAApplication.class);

生成以下JSON,不带双引号,因此服务器发送400 Bad Request。

{ applications:
[ { submissionDate: '2014-09-05T08:28:17',
   firstName: 'Mickey',
   lastName: 'Mouse',
   email: 'mm@disney.com',
   dietaryRestrictions: 'Cheese only',
   restSkillLevel: 'Novice',
   jsonSchemaSkillLevel: 'Expert',
   restStandardFamiliarity: true,
   slimFamiliarity: true,
   odataLibFamiliarity: true } ] }

1 个答案:

答案 0 :(得分:0)

您的客户端代码工作得很好。 400 Bad请求可能是由于您的控制器端可能无法处理内容而导致的错误。

您粘贴在上面的JSON没有双引号,因为有些编辑器或程序只是为了提高可读性而呈现JSON。通过postForEntity序列化后的原始字符串实际上是生成带双引号的JSON。

下面提到的代码正在运行,我通过编写测试来测试它。

package com.test.rest.controller;

import com.fasterxml.jackson.annotation.JsonInclude;
import ........    

public class TestAppController {

@Test
public void testController() throws Exception {

    Server mockServer = new Server(9190);
    startMockServer("query-rs-main.xml", "query-rs", mockServer);

    EAApplication requestEntity = new EAApplication();
    Application application = new Application();
    application.setDietaryRestrictions("Cheese only");
    application.setFirstName("Mickey");
    application.setLastName("Mouse");
    application.setEmail("mm@disney.com");
    application.setJsonSchemaSkillLevel("Expert");
    application.setRestSkillLevel("Novice");
    application.setSubmissionDate(new Date());
    application.setOdataLibFamiliarity(true);
    application.setRestStandardFamiliarity(true);

    List<Application> list = new ArrayList<>();
    list.add(application);

    requestEntity.setApplications(list);

    RestTemplate template = new RestTemplate();

    List<HttpMessageConverter<?>> converters = new ArrayList<HttpMessageConverter<?>>();
    MappingJackson2HttpMessageConverter mappingJacksonHttpMessageConverter = new MappingJackson2HttpMessageConverter();
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
    mappingJacksonHttpMessageConverter.setObjectMapper(objectMapper);
    mappingJacksonHttpMessageConverter.setPrettyPrint(true);
    converters.add(mappingJacksonHttpMessageConverter);
    template.setMessageConverters(converters);

    ResponseEntity<EAApplication> response = template.postForEntity(
            "http://localhost:9190/query-rs/eaapps",
            requestEntity, EAApplication.class);

    mockServer.stop();

}

public static void startMockServer(final String mainAppContextConfig, final String contextRoot, Server server) throws Exception {
    final DispatcherServlet servlet = new DispatcherServlet();
    servlet.setContextConfigLocation("classpath:" + mainAppContextConfig);
    final ServletHolder servletHolder = new ServletHolder(servlet);

    final ServletContextHandler context = new ServletContextHandler();
    context.setErrorHandler(null);
    context.setContextPath("/" + contextRoot);
    context.addServlet(servletHolder, "/*");

    server.setHandler(context);
    server.start();
}


}

服务器端的控制器 -

package com.yt.nss.rest.query.mock.controller;


import org.springframework.http.HttpStatus;
import ....

@Controller
@RequestMapping("/eaapps")
public class EAApplicationsController {


@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<Object> submitMessage(final @RequestBody EAApplication eaApplication) {

    System.out.println(eaApplication);
    return new ResponseEntity<Object>(null, HttpStatus.OK);
}

}

用于传输JSON的EAApplication类或POJO

@XmlRootElement
public class EAApplication {
private List<Application> applications;

public List<Application> getApplications() {
    return applications;
}

public void setApplications(List<Application> applications) {
    this.applications = applications;
}

@Override
public String toString() {
    return "EAApplication{" +
            "applications=" + applications +
            '}';
}
}

当我运行客户端和服务器时,已成功调用控制器,并且控制器方法上的EAApplication对象已完全填充。

我建议您在服务器端查看控制器和弹簧mvc配置,或在此处发布。