1

Is there a JSON library for Java that can handle something like the following scenario:

public class BaseShapeSender<T extends Shape> {
{
  Collection<T> shapes;

  public void send
  {
    // Sending the shapes collection with JSON
  }
}

public class CircleSender extends BaseShapeSender<Circle>
{

}

Currently I'm using Jersey, but calling circleSender.send() with the above above scenario gives an exception

A message body writer for Java type, class java.util.ArrayList, and MIME media type, application/json, was not found

even when using GenericEntity to send the collection (apparently Jersey can handle Collection<Circle> but the second level of generics is too much). So, I found myself duplicating the sending code in every subclass:

public class CircleSender extends BaseShapeSender<Circle>
{
  Collection<Circle> circles;

  public void send
  {
    // Sending the circles collection with JSON
  }
}

I would love to avoid that if possible since the sending logic is basically the same in all subclasses.

Alex
  • 1,041
  • 3
  • 14
  • 32

2 Answers2

2

One of the best JSON library for Java is Jackson (http://jackson.codehaus.org).

We use it with Jersey and Resteasy and it's very good. You may automate object transformation without writing any factory or extra code. It's just automatic. There are a lot of advanced features and it is proven. I believe it is the standard for Java.

It also supports templating. Here is an example:

List<User> list = getUserService().getAllUsers();
Writer writer = new StringWriter();
getObjectMapper().writeValue(writer, list);
unludo
  • 4,912
  • 7
  • 47
  • 71
  • How does it integrate with Jersey? Don't they perform the same job (serializing Java objects to JSON strings and vice versa)? – Alex Feb 03 '12 at 08:19
  • No in fact Jersey manages the REST part. You need to convert the argurments (both input and output if you want to convert from/to JSON). When you convert the output to a string with Jackson, return it in the REST controller and is is sent in response. I found an example here http://www.mkyong.com/webservices/jax-rs/json-example-with-jersey-jackson/. I mainly use Resteasy which is a bit different. – unludo Feb 03 '12 at 08:32
1

According to this answer Jackson supports both generics as well as polymorphism. GSON (which I've stuck with so far) does not until issue 231 is resolved.

Community
  • 1
  • 1
Ben Schulz
  • 6,101
  • 1
  • 19
  • 15