Vítor Marques
Vítor Marques

Reputation: 349

JSON Parsing with JAX-RS

I am building an REST API with JAX-RS. I have POST that consumes an JSON element:

The element is a class:

@XmlRootElement
public class EventData{
   public long start;
   public long end;
   public Collection<Person> persons;
}

I have an method like this:

@POST
@Consumes({MediaType.APPLICATION_JSON})
public Response transactionRequest(EventData insert){
....}

if I post a JSON String of an EventData it works fine, but if I switch to:

@POST
@Consumes({MediaType.APPLICATION_JSON})
public Response transactionRequest(ArrayList<EventData> insert){
....}

and send an JSON String like this "{eventData:[{start:x,end:y,persons:[....]}]" it will build the ArrayList and its EventData objects, but the EventData object variables are null.

Can anybody help?

Upvotes: 3

Views: 6487

Answers (1)

Philipp Reichart
Philipp Reichart

Reputation: 20961

You need to send a JSON array consisting of JSON objects representing your EventData class.

The sample you've given isn't such a JSON array, but a JSON object with a single property named 'eventData' containing an JSON array.

Try something like this (based on your EventData class):

[
  { "start":1, "end":2, "persons":[] },
  { "start":3, "end":4, "persons":[] }
]

Notice that there is no mention of your EventData class, because JSON has no concept of named types -- it's just objects and arrays of objects; only the properties of objects have names.

Upvotes: 1

Related Questions