11 votes

Jax-rs(Jersey) pour consommer un tableau d'objets Json dans une requête POST.

En utilisant le jax-rs(Jersey), j'essaie d'implémenter une requête POST qui prend une liste d'objets JSON.

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

Cependant, lorsque j'essaie de tester l'api REST à l'aide de curl, j'obtiens toujours une erreur de type "mauvaise requête".

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

4voto

user311174 Points 757

Si cela ne vous dérange pas de changer la signature de votre méthode :

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

2voto

Harun Daloğlu Points 21

Une réponse tardive mais qui peut être utile pour d'autres Affichez ceci :

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

Parce qu'en envoyant ça :

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

Vous publiez un objet avec une seule propriété nommée 'SomeObj'. Vous ne publiez pas un tableau.

0voto

guilhebl Points 372

Essayez de placer votre tableau JSON dans un objet, par exemple :

@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

-3voto

F. P. Freely Points 74

Du côté du serveur :

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
}

Et du côté du client :

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

Prograide.com

Prograide est une communauté de développeurs qui cherche à élargir la connaissance de la programmation au-delà de l'anglais.
Pour cela nous avons les plus grands doutes résolus en français et vous pouvez aussi poser vos propres questions ou résoudre celles des autres.

Powered by:

X