English 中文(简体)
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?

最佳回答

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!

问题回答

This has changed since the accepted answer was written.

If you turn on the pojoMappingFeature the objectMapper will be automatically invoked by jersey. In a servlet environment do the following inside your jersey definition:

<init-param>
    <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
    <param-value>true</param-value>
</init-param>

You can now simply return the feeds from the endpoint.

@GET
@Produces(MediaType.APPLICATION_JSON)
public Collection<CalendarFeeds> getCalendars() {
    Member member = memberService.getCurrentMember();
    return member.getCalendarFeeds();
}




相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签