Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate JSON from a Jersey resource?

I'm using Jersey and want to output the following JSON with only the fields listed:

[
    {
      "name": "Holidays",
      "value": "http://www.google.com/calendar/feeds/usa__en%40holiday.calendar.google.com/public/basic"
    },
    {
      "name": "Personal",
      "value": "http://www.google.com/calendar/feeds/myprivatefeed/basic"
    }
]

If I must, I can surround that JSON with {"feeds": ... }, but having this be optional would be best. I want to pull this information from a list of CalendarFeeds that are stored in a Member POJO that is retrieved via Hibernate. Here are the simplified POJOs:

public class Member {
    private String username;
    private String password;
    private Set<CalendarFeed> calendarFeeds = new HashSet<CalendarFeed>();
}

public class CalendarFeed {
    public enum FeedType { GCAL, EVENT };
    private Member owner;
    private String name;
    private String value;
    private FeedType type;
}

Currently, I've got a Jersey resource called CalendarResource that manually outputs JSON with the calendar feeds information:

@Path("/calendars")
public class CalendarResource {

    @Inject("memberService")
    private MemberService memberService;

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public String getCalendars() {
        // Get currently logged in member
        Member member = memberService.getCurrentMember();

        StringBuilder out = new StringBuilder("[");
        boolean first = true;
        for (CalendarFeed feed : member.getPerson().getCalendarFeeds()) {
            if (!first) {
                out.append(",");
            }
            out.append("{\"");
            out.append(feed.getName());
            out.append("\":\"");
            out.append(feed.getValue());
            out.append("\"}");
            first = false;
        }
        out.append("]");
        return out.toString();
    }
}

But I'm not sure how to go about automating this. I'm just starting to use Jersey and am not clear on how to use it to return JSON. It sounds like it has a way to do this built in, but it looks like I need to add annotations to my POJOs. Also, I read others saying that I need to use Jackson. I've been googling and can't seem to locate a good and simple example of returning JSON from a Jersey resource. Anyone know of any? Or can you show me how to use Jackson or Jersey to create JSON for for the above example?

like image 424
Tauren Avatar asked Jan 23 '10 00:01

Tauren


People also ask

What is Jersey JSON?

Jersey JSON support comes as a set of JAX-RS MessageBodyReader<T> and MessageBodyWriter<T> providers distributed with jersey-json module. These providers enable using three basic approaches when working with JSON format: POJO support. JAXB based JSON support. Low-level, JSONObject/JSONArray based JSON support.

Does Jersey use Jackson?

Jersey uses Jackson internally to convert Java objects to JSON and vice versa.


1 Answers

I figured out how to do this using Jackson 1.4. I'm not using jersey-json since it is based on an older version of Jackson and I needed version 1.4 to use JsonViews.

Here is the annotated pojo:

public class CalendarFeed {
    public enum FeedType { GCAL, EVENT };
    @JsonIgnore
    private Member owner;
    private String name;
    private String value;
    @JsonIgnore
    private FeedType type;
}

Here is the jersey resource:

@Path("/calendar")
public class CalendarResource {

 @Inject("memberService")
 private MemberService memberService;

 @Inject
 private ObjectMapper mapper;

 @GET
 @Produces(MediaType.APPLICATION_JSON)
 public String getCalendars() {
  Member member = memberService.getCurrentMember();
  try {
   return mapper.writeValueAsString(member.getCalendarFeeds());
  } catch (JsonGenerationException e) {
  } catch (JsonMappingException e) {
  } catch (IOException e) {
  }
  return "{}";
 }
}

Here is my spring bean:

<!-- Jackson JSON ObjectMapper -->
<bean id="objectMapper" class="org.codehaus.jackson.map.ObjectMapper"/>

The output is exactly what I need. And using JsonViews, I can customize what fields get output for different situations.

Hopefully this will help someone else!

like image 200
Tauren Avatar answered Sep 24 '22 14:09

Tauren