【发布时间】:2017-05-12 17:10:12
【问题描述】:
我正在使用POST 将对象作为参数发送到服务中的方法。该方法每次都会调用,但 spring 会返回一个初始化对象(带有零和空值),而不是服务返回的对象。
邮递员工作得很好:
我发送:
{
"userId": 10,
"resourceType": 11,
"privilegeValues": [
1,
2,
3
]
}
我明白了:
{
"ErrorCode": 10,
"ErrorDescription": null,
"Privilages": [
1,
2,
3
]
}
C#:
IPrivilagesRest:
namespace RestAPI
{
[ServiceContract(Namespace = "http://microsoft.wcf.documentation")]
public interface IPrivilagesRest
{
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "/GetUserPrivilages", RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
UserPrivilegesResponse GetUserPrivilages(UserPrivilegesRequest userPrivilegesRequest);
[OperationContract]
[WebInvoke(Method = "GET", UriTemplate = "/IsAlive", RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
bool isAlive();
}
}
PrivilagesProvider:
namespace RestAPI
{
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class PrivilagesProvider : IPrivilagesRest
{
/// <summary>
/// get privilages related to a specific user.
/// </summary>
/// <param name="userPrivilegesRequest"></param>
/// <returns></returns>
public UserPrivilegesResponse GetUserPrivilages(UserPrivilegesRequest userPrivilegesRequest)
{
Console.Clear();
Console.WriteLine(userPrivilegesRequest==null?"Null":"Not null!!!!!!!");
return new UserPrivilegesResponse() { Privilages = new int[] { 1, 2, 3 },ErrorCode=10 };
}
public bool isAlive()
{
return true;
}
}
}
Application.java
@SpringBootApplication
public class Application {
private static final Logger log = LoggerFactory.getLogger(Application.class);
public static void main(String args[]) {
SpringApplication.run(Application.class);
}
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
return builder.build();
}
@Bean
public CommandLineRunner run(RestTemplate restTemplate) throws Exception {
return args -> {
UserPrivilegesRequest request=new UserPrivilegesRequest();
UserPrivilegesResponse response = restTemplate.postForObject("http://localhost:12345/PrivilagesServiceNamespace/PrivilagesService/GetUserPrivilages",request, UserPrivilegesResponse.class);
log.info("respose: "+ response);
};
}
}
UserPrivilegesResponse.java
@ToString
public class UserPrivilegesResponse {
@Getter
@Setter
private int ErrorCode;
@Getter
@Setter
private int ErrorDescription;
@Getter
@Setter
private int[] Privilages;
}
【问题讨论】: