使用MultivalueMap进行后调用问题

时间:2016-05-31 05:45:00

标签: java rest jax-rs restlet

我在服务中遇到问题。 以下是我的服务

@POST
@Path("/config")
@Consumes(MediaType.APPLICATION_JSON)
public Response saveConfiguration(String name, MultivaluedMap<String,
  Object> properties) {
     return Response.ok().build();
}

我的测试用例是:

String payload = "{"name": "CRJ001", 
  "properties": {"expression": ["a + b"], 
  "baseClass": ["org.carlspring.strongbox.crontask.test.MyTask"]}}";

WebTarget resource = client.getClientInstance().target(path);
Response response = resource.request(MediaType.APPLICATION_JSON).
   post(Entity.entity(payload, MediaType.APPLICATION_JSON));

int status = response.getStatus();
assertEquals("Failed to save!", Response.ok().build().getStatus(), status);

但我得到了:

[[FATAL] Method public javax.ws.rs.core.Response org.abc.rest.ConfigurationRestlet.
  saveConfiguration(java.lang.String,javax.ws.rs.core.MultivaluedMap) 
  on resource class org.abc.rest.ConfigurationRestlet contains multiple
  parameters with no annotation. Unable to resolve the injection source.;

请帮我解决这个问题

1 个答案:

答案 0 :(得分:2)

您要实现的是从POST方法的JSON有效负载将多个参数映射到REST API, 这是不可能的,请查看this answer了解详细信息。

我知道您要传递属性列表;上述答案并不适合您的情况,

我的建议是:将您的 名称 参数转换为路径参数查询参数取决于它是否是可选的。

所以你应该像这样加强它:

路径参数(如果名称参数是必填项)

@POST
@Path("/config")
@Consumes(MediaType.APPLICATION_JSON)
public Response saveConfiguration(@PathParam("name") String name, MultivaluedMap<String,
  Object> properties) {
     return Response.ok().build();
}

查询参数(如果名称​​参数是可选的)

@POST
@Path("/config/{name}")
@Consumes(MediaType.APPLICATION_JSON)
public Response saveConfiguration(@QueryParam("name") String name, MultivaluedMap<String,
  Object> properties) {
     return Response.ok().build();
}

在这种情况下,名称将作为您的请求的查询参数传递:

POST ... / config?name = name1

并且显然在这两种情况下,您都不应该在JSON有效负载中传递“name”参数。

相关问题