【问题标题】:Jax-rs(Jersey) to Consumes Array of Json object in POST requestJax-rs(Jersey) 在 POST 请求中使用 Json 对象数组
【发布时间】:2012-06-29 12:40:28
【问题描述】:

使用 jax-rs(Jersey) 我尝试实现一个获取 JSON 对象列表的 POST 请求

//The resource look like this
@Path("/path")
@POST
@Consumes(MediaType.APPLICATION_JSON)
public void setJsonl(List<SomeObj> test) {
  //do work
  System.out.println(test);
}


//The class to define the json structure
@XmlRootElement
public class SomeObj{

private String tag;
private String value;

public String getTag() {
 return tag;
}

public void setTag(String tag) {
  this.tag = tag;
}

public String getValue() {
  return value;
}

public void setValue(String value) {
  this.value = value;
}
}

当我尝试使用 curl 测试 REST api 时,我总是收到“错误请求”错误,我在这里遗漏了什么吗?

curl -X POST -H "Content-Type: application/json" -d '{"SomeObj":[{"tag":"abc", "value":"ghi"},{"tag":"123", "value":"456"}]}' http://{host_name}:8080/path_to_resource

【问题讨论】:

  • 那么,你是怎么解决的呢?根据 user311174 的回答,不支持 json 的直接映射。这是真的吗?

标签: java rest jersey jax-rs


【解决方案1】:

尝试将您的 JSON 数组包装在一个对象中,例如:

@XmlRootElement 
public class SomeObjListWrapper {
private List<SomeObj> list;
// getters and setters
}

curl -X POST -H "Content-Type: application/json" -d '{"list":[{"tag":"abc", "value":"ghi"},{"tag":"123", "value":"456"}]}' http://{host_name}:8080/path_to_resource

【讨论】:

    【解决方案2】:

    迟到的答案,但可能对其他人有帮助 发布这个:

    [{"tag":"abc", "value":"ghi"},{"tag":"123", "value":"456"}]

    因为发送这个:

    {"SomeObj":[{"tag":"abc", "value":"ghi"},{"tag":"123", "value":"456"}]}

    您正在发布一个具有单个“SomeObj”命名属性的对象。你没有发布数组

    【讨论】:

    • 对于像我这样的人现在面临同样的问题,这个答案是为我工作的人。我目前正在将 Jax-RS (Resteasy) 与 JBoss EAP 6.3 一起使用;D
    • 但是你如何支持 application/xml 呢?这样我只能发布 json 而不能发布 xml
    【解决方案3】:

    在服务器端:

    import _root_.org.codehaus.jettison.json.{JSONArray, JSONObject}
    @POST
    @Path("/wants-json-array")
    @Consumes(Array(MediaType.APPLICATION_JSON))
    def wantsJSONArray(array: JSONArray): Response =
    {
        // here's your array
    }
    

    在客户端:

    $.ajax(
    {
        type: "GET",
        url: '/your-web-service/wants-json-array',
        data: JSON.stringify(THEARRAYYOUARESENDINGTOTHESERVER),
        contentType: "application/json",
        dataType: "json",
        processData: false
    });
    

    【讨论】:

      【解决方案4】:

      如果您不介意更改方法的签名:

      import org.json.JSONArray;
      
          //The resource look like this
          @Path("/path")
          @POST
          @Consumes(MediaType.APPLICATION_JSON)
          public void setJsonl(String array){
              JSONArray o = new JSONArray(last_data);
              System.out.println(o.toString());
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-04-07
        • 2019-04-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-14
        • 1970-01-01
        • 2017-05-08
        相关资源
        最近更新 更多