[英]How to parse JSON array using Jersey Rest Webservices and Java
[英]Converting incoming JSON to Java array using Jersey
我有一個REST api GET調用,該調用接受一組格式為JSON的字符串。 我想使用Jersey將字符串數組轉換為類似字符串數組或List的內容。 我已經審查了http://jersey.java.net/nonav/documentation/latest/json.html ,但是看來Jersey希望我創建一個對象,該對象指定應如何映射它,我真的不想要之所以這樣做,是因為它只是一個簡單的數組。
@GET
public Response get(@QueryParam("json_items") String requestedItems) throws IOException
{
//Would like to convert requestedItems to an array of strings or list
}
我知道有很多與此相關的庫-但是我更喜歡使用Jersey而不引入任何新庫。
為您的數據創建一個包裝對象(在本例中為Person類),並使用@XMLRootElement對其進行注釋
您的發布方法應如下所示
@POST
@Consumes(MediaType.APPLICATION_JSON)
public void post(List<Person> people) {
//notice no annotation on the method param
dao.putAll(people);
//do what you want with this method
//also best to return a Response obj and such
}
這是在請求中發送數據的正確方法。
但是,如果您希望將QueryParam作為JSON數據,則可以執行此操作
說您的請求參數如下所示:字符串person =“ {\\” person \\“:[{\\” email \\“:\\” asdasd@gmail.com \\“,\\” name \\“:\\” asdasd \\“}, {\\“電子郵件\\”:\\“ Dan@gmail.com \\”,\\“名稱\\”:\\“ Dan \\”},{\\“電子郵件\\”:\\“ Ion@gmail.com \\”,\\“名稱\\“:\\” dsadsa \\“},{\\”電子郵件\\“:\\” Dan@gmail.com \\“,\\”名稱\\“:\\” ertert \\“},{\\”電子郵件\\“:\\”離子@ gmail.com \\“,\\”名稱\\“:\\”離子\\“}]}”;
您會注意到,它的JSONObject名為“ person”,其中包含Person類型的其他JSONObjets的JSONArray,名稱為email:P,您可以像這樣對它們進行設置:
try {
JSONObject request = new JSONObject(persons);
JSONArray arr = request.getJSONArray("person");
for(int i=0;i<arr.length();i++){
JSONObject o = arr.getJSONObject(i);
System.out.println(o.getString("name"));
System.out.println(o.getString("email"));
}
} catch (JSONException ex) {
Logger.getLogger(JSONTest.class.getName()).log(Level.SEVERE, null, ex);
}
ry
只需嘗試將數組添加到您的Response中,例如
return Response.ok(myArray).build();
看看會發生什么。 如果它只是一個非常簡單的數組,則應毫無問題地對其進行解析。
編輯:
如果要接收它,則只需接受一個數組而不是一個String。 嘗試使用列表或類似的方法。
否則,您可以嘗試使用ObjectMapper解析它
mapper.readValue(string, List.class);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.