0

I'm using a Jersey (v 1.17.1) client to communicate with a remote server that I don't have under my control (so I can't see the incomming requests).

I like to issue a POST request with JSON data, that has a structure similar to this example:

{"customer":"Someone",
 "date":"2013-09-12",
 "items":[{
     "sequenceNo":1,
     "name":"foo",
     "quantity":2,
     "price":42,
     "tax":{"percent":7,"name":"vat 7%"}
   },
   {
     "sequenceNo":2,
     "name":"bar",
     "quantity":5,
     "price":23,
    "tax":{"percent":7,"name":"vat 7%"}
   }
 ]
}

That's my code:

final Client c = Client.create();
final WebResource service = c.resource(SERVER);

final Form form = new Form();
form.add("customer", "Someone");
form.add("date", "2013-09-12");
form.add("items", XXX); // how do I do that?

final ClientResponse response = service.path("aPath").queryParam("param", "value").cookie(new Cookie("token", token))
        .type(MediaType.APPLICATION_JSON)
        .post(ClientResponse.class, form);
    final String raw = response.getEntity(String.class);
    System.out.println("Response " + raw);

I tried several approaches (like nesting another Form object), but I always get the same result: The server returns 400 - Bad Request ("The request sent by the client was syntactically incorrect (Bad Request).") I assume because the mandatory parameter items isn't sent correctly.

Does somebody know how I nest JSON data like described? I think it is a common case, but I found no examples in the web.

Steffzilla
  • 75
  • 3
  • 9
  • I'm still looking for the solution but this [answer](http://stackoverflow.com/questions/6860661/jersey-print-the-actual-request/6873911#6873911) is helpful: It enables client side logging – Steffzilla Sep 13 '13 at 08:25

1 Answers1

0

Form is essentially a Map that limits your values to Strings. What you need is a simple Map (e.g. a HashMap). Every nested element will also be a map. So you will have something like this.

Map<String, Object> data = new HashMap<String, Object>();
data.put("customer", "Someone");
data.put("date", "2013-09-12");

Map<String, Object> item1 = new HashMap<String, Object>();
item1.put("sequenceNo", 2);
item1.put("name", "foo");

data.put("items", Arrays.asList(item1));

This way you can do as much nesting as you need.

Alternatively you can create a few classes that represent your data structures. Jersey will know how to serialize it.

class Item {
  String name;
  int sequenceNo;
  // getters & setters
}

class Data {
  String customer;
  String date;
  List<Item> items;
  // getters & setters
}
kkamenev
  • 939
  • 9
  • 12