i'm trying to transfer a list of objects from a server to a client using a web service.
The data should be transfered in json format.
I'm using jersey for the JAX-RS implementation and gson to deserialise the json string on the client side.
I kept getting a parse error, even though i was using the recommended practice for list deserilization with gson (see below).
I have found out that the json string which i am getting in the response is different than the one which i should receive in order for the gson deserilizer to work.
This is the reponse i'm getting from the web service:
{"activity":[{"activityName":"c","id":"3"},{"activityName":"c","id":"3"},{"activityName":"c","id":"3"}]}
But this is the correct response i should receive in order for the gson to deserialize the string to a List:
[{"id":3,"activityName":"c"},{"id":3,"activityName":"c"},{"id":3,"activityName":"c"}]
You can see the added header/wrapper "activity" in the begining of the first string.
Here is the web service code:
@Path("ws")
public class IiwsServices {
@POST
@Path("/listActivities")
@Produces(MediaType.APPLICATION_JSON)
public List<Activity> listActivities() {
List<Activity> list = new ArrayList<Activity>();
Activity act = new Activity();
act.setId(1);
act.setActivityName("a");
list.add(act);
act.setId(2);
act.setActivityName("b");
list.add(act);
act.setId(3);
act.setActivityName("c");
list.add(act);
return list;
}
This is the client code:
public class Main {
public static void main(String[] args) {
try {
Client client = Client.create();
WebResource webResource = client
.resource("http://localhost:8080/iiws.ws.test/ws/listActivities");
ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON)
.post(ClientResponse.class);
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatus());
}
String output = response.getEntity(String.class);
System.out.println(output);
List<Activity> list = new ArrayList<Activity>();
Activity act = new Activity();
act.setId(1);
act.setActivityName("a");
list.add(act);
act.setId(2);
act.setActivityName("b");
list.add(act);
act.setId(3);
act.setActivityName("c");
list.add(act);
Gson gson = new GsonBuilder().create();
String jsonString = gson.toJson(list);
System.out.println(jsonString);
List<Activity> list = gson.fromJson(output, new TypeToken<List<Activity>>(){}.getType()); // <-- Deserialize exception here
for (int i = 0; i < list.size(); i++) {
Activity x = list.get(i);
System.out.println(x);
}
} catch (Exception e) {
e.printStackTrace();
}
}
****OK I believe I have found the answer****
OK finally found solution
Here i found a similar question after googling for jersey and jackson :
Jersey client can not deserializable json services
And this helps as well:
JSON POJO support
Button line is that if not explicitely defined in the web.xml, jersey+jaxb is used instead of jersey+jackson