【发布时间】:2018-09-16 11:38:51
【问题描述】:
春季 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。在控制器中,我也将 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"
}]}
看起来杰克逊序列化器正在干扰响应并引发上述错误。
解决办法是什么?
【问题讨论】: