我很難接受JSON輸入到我的Spring Restful Web服務中。基本上我的目的是接受一個JSON並返回一個zip文件。但我無法跨越自己的第一步。 以下是控制器代碼如何在Spring Restful Webservice中接受JSON輸入?
@Controller
@RequestMapping(value = "/request")
public class PasskitController {
@Autowired
@Qualifier("PassManager")
private PassManager pm;
/*headers = { "Accept:application/json" },
consumes = MediaType.APPLICATION_JSON_VALUE,*/
@RequestMapping(value = "/createPass", method = RequestMethod.POST,
consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
public @ResponseBody ByteArrayOutputStream createGiftPass(
@RequestBody PassGenerationRequest request) throws IOException {
System.out.println("in createGiftPass() method");
String success = "Success";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write(success.getBytes());
return baos;
}
@RequestMapping(value = "/test", method = RequestMethod.GET,
produces = MediaType.TEXT_PLAIN_VALUE)
public @ResponseBody
String test() throws IOException {
System.out.println("in test() method");
return "Success";
}
}
我需要輸入JSON映射到以下POJO PassGenerationRequest
@JsonAutoDetect
public class PassGenerationRequest {
private String serialNumber;
private String upc;
private String campaign;
private String merchant;
public String getSerialNumber() {
return serialNumber;
}
public void setSerialNumber(String serialNumber) {
this.serialNumber = serialNumber;
}
public String getUpc() {
return upc;
}
public void setUpc(String upc) {
this.upc = upc;
}
public String getCampaign() {
return campaign;
}
public void setCampaign(String campaign) {
this.campaign = campaign;
}
public String getMerchant() {
return merchant;
}
public void setMerchant(String merchant) {
this.merchant = merchant;
}
}
以下是在彈簧servlet.xml中配置的不同HttpMessageConverters
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jsonMessageConverter" />
<ref bean="byteArrayMessageConverter"/>
<ref bean="stringMessageConverter"/>
</list>
</property>
</bean>
<bean id="jsonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" >
<property name="supportedMediaTypes" value="application/json" />
</bean>
<bean id="byteArrayMessageConverter"
class="org.springframework.http.converter.ByteArrayHttpMessageConverter" >
<property name="supportedMediaTypes" value="application/octet-stream" />
</bean>
<bean id="stringMessageConverter"
class="org.springframework.http.converter.StringHttpMessageConverter" >
<property name="supportedMediaTypes" value="text/plain" />
</bean>
目前我得到內容類型'text/plain;字符集= UTF-8'不支持異常。
如果我添加了頭= {「接受:應用/ JSON」}然後我得到異常說沒有處理程序爲請求找到「請求/ createPass」
誰能請在幫助我這裏?
謝謝。
什麼是你的要求是什麼樣子? –
我實際上是使用郵遞員應用程序發佈我的請求。 – user2985202