gpt4 book ai didi

Java Spring POST API json 输入

转载 作者:太空宇宙 更新时间:2023-11-04 13:49:07 25 4
gpt4 key购买 nike

首次开发基于java spring的API。这些 API 将采用 POST 方式并采用 JSON 作为输入。我不能连接所有点,因为当我从其余客户端调用 api 调用时会出现错误消息。

pom.xml

      <dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.5.3</version>
</dependency>

从 json 序列化的对象

public class PostCountry {
private String country;


public void setCountry(String country){
this.country=country;
}
public String getCountry() {
return country;
}

}

Controller

@RequestMapping(value = "/getCountries", method = RequestMethod.POST, consumes = "application/json")
public @ResponseBody String getCountries(PostCountry country) {
System.out.println(country.getCountry());
MapDAOImpl mapDAOImpl = (MapDAOImpl) appContext.getBean("mapDAOImpl");
System.out.println(mapDAOImpl.getCountries(country.getCountry()));
return "";

}

休息客户端抛出错误消息

<u>The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.</u>

Rest call

错误

System.out.println(country.getCountry()); is null

最佳答案

问题有 2 倍。我需要在 xml 文件中定义一些 RequestMappingHandlerAdapter。

  <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>
<bean class="org.springframework.http.converter.xml.SourceHttpMessageConverter"/>
<bean class="org.springframework.http.converter.FormHttpMessageConverter"/>
<bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
</list>
</property>
</bean>

并在模型中定义一个空的构造函数

public class PostCountry {


public String country;

public PostCountry() {}

public PostCountry(String country) {
this.country = country;
}

public void setCountry(String country){
this.country=country;
}
public String getCountry() {
return country;
}

}




@RequestMapping(value = "/getCountries"
, method = RequestMethod.POST
, consumes = "application/json"
, produces = "application/json")
@ResponseBody
@JsonIgnoreProperties(ignoreUnknown = true)
public ReturnCountries getCountries(@RequestBody PostCountry country) {

关于Java Spring POST API json 输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30509639/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com