簡體   English   中英

Jax-rs(Jersey)消耗POST請求中的Json對象數組

[英]Jax-rs(Jersey) to Consumes Array of Json object in POST request

使用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

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

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());

一個遲到的答案,但可能對其他人有幫助發布這個:

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

因為發送這個:

{“SomeObj”:[{“tag”:“abc”,“value”:“ghi”},{“tag”:“123”,“value”:“456”}}}

您正在發布一個具有單個“SomeObj”命名屬性的對象。 你沒有發布數組

嘗試將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

在服務器端:

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
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM