簡體   English   中英

Spring-將Pojo轉換為JSON時出現問題(未找到轉換器錯誤)

[英]Spring - Problem converting a pojo to a JSON (No converter found error)

春天4.3.3

我正在嘗試將Pojo轉換為JSON,將Controller標記為
@RestController,問題在於某些元素的首字母小寫而不是大寫,

Ex:
"Id": 1, //This is ok  
"customerId": "1234", //Instead of CustomerId, this has customerId
...

調節器

@RestController
...
public class CustomerController{
    ...
    @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
    public CustomerResponse postCustomerRequest(final HttpServletRequest request) { 

我希望大寫。 pojo基本上是xsd的xjc生成的類,它包含

@XmlElement(name = "Id")
protected int id;
@XmlElement(name = "CustomerId")
protected String customerId;
...
    public int getId() {
        return id;
    }
    public void setId(int value) {
        this.id = value;
    }
    public String getCustomerId() {
        return customerId;
    }
    public void setCustomerId(String value) {
        this.customerId = value;
    }

每個屬性都有關聯的setter,getter。 在Controller中,我也將不區分大小寫的ObjectMapper設置為true,

mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true); 

我也嘗試過,將Controller標記為@Controller而不是@RestController,在方法之前提供@ResponseBody,

調節器

@Controller
...
public class CustomerController {
...
    @Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
    @ResponseBody
    public String postCustomerRequest(HttpServletRequest request) {
        ...

//Used PropertyNamingStrategy with the ObjectMapper, converted the first character to an upper case, 
            ObjectMapper mapper = new ObjectMapper();
            mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
            ...
            CustomerResponse response=createCustomer(document,objectFactory);
            mapperObj.setPropertyNamingStrategy(new CustomerJsonNameStrategy());
            String jsonOutput = mapperObj.writeValueAsString(response);
            return jsonOutput;

如果我在Eclipse調試期間看到jsonOutput的值,則它以正確的大小寫輸出json元素,但是對其余客戶端的響應如下:

{"errors": [{
   "message": "No converter found for return value of type: class java.lang.String",
   "type": "IllegalArgumentError"
}]}

看起來傑克遜連載人干擾了響應並拋出了以上錯誤。

有什么解決方案?

Spring使用Jackson將POJO轉換為json。 默認情況下,Jackson使字段名的第一個字母變小。 如果需要自定義名稱,請添加以下傑克遜注釋。

@JsonProperty("CustomerId")
private String customerId; 

在這種情況下,@ Consumes對您沒有太大幫助。 它應該用於指定輸入格式。 檢查本文: http : //www.javainterviewpoint.com/jax-rs-rest-consumes-example/

如果在調試過程中可以看到jsonOutput,則問題可能與客戶端期望輸出的方式有關:客戶端可能期望使用JSON而不是String對象。 解決方案:返回CustomerResponse而不是String。

@RestController
...
public class CustomerController {
  ...
  public CustomerResponse postCustomerRequest(final HttpServletRequest request) 
{

如果要更改默認命名,則CustomerResponse和CustomerResponse的字段應帶有@JsonProperty注釋。

@JsonProperty(name = "Id")
protected int id;

@JsonProperty(name = "CustomerId")
protected String customerId;

我將使用您的自定義屬性命名策略配置MappingJackson2HttpMessageConverter ,在IMHO中,與在每個控制器方法中序列化為json相比,這是更清潔的解決方案

<mvc:annotation-driven>
    <mvc:message-converters>
        ...
        <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
            <property name="objectMapper" ref="objectMapper"/>
        </bean>
        ...
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

<bean id="objectMapper" class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
    <property name="propertyNamingStrategy" ref="customNamingStrategy" />
</bean

或者,如果您確實想要或需要控制響應主體,請確保在Spring MVC配置中將StringHttpMessageConverter注冊為轉換器。

<mvc:annotation-driven>
     <mvc:message-converters>
            ...
            <bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
            ...
   </mvc:message-converters>
</mvc:annotation-driven>

我通過移動到沒有傑克遜設置的擴展程序來使其工作。 PS:這在SAP Hybris中,並且包含多個擴展/項目。

我用@Controller標記了Controller,添加了@Produces({MediaType.APPLICATION_JSON}),刪除了@ResponseBody,將方法返回類型設置為ResponseEntity,使用PropertyNamingStrategy轉換了大寫的第一個字母。

public ResponseEntity<String> postCustomerRequest(final HttpServletRequest request) {
    ...
    final org.codehaus.jackson.map.ObjectMapper mapperObj = new org.codehaus.jackson.map.ObjectMapper();
    CustomerResponse response=createCustomer(document,objectFactory);
    mapperObj.setPropertyNamingStrategy(new CustomerJsonNameStrategy());

    final HttpHeaders httpHeaders= new HttpHeaders();
    httpHeaders.setContentType(org.springframework.http.MediaType.APPLICATION_JSON);
    return new ResponseEntity<String>(mapperObj.writeValueAsString(response), httpHeaders, HttpStatus.OK);

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM