如何从 Jersey 资源生成 JSON?

发布于 2024-08-19 02:20:18 字数 1945 浏览 10 评论 0原文

我正在使用 Jersey,并且希望输出以下 JSON,仅包含列出的字段:

[
    {
      "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"
    }
]

如果必须,我可以用 {"feeds": ... } 包围该 JSON,但最好将其设为可选。我想从存储在通过 Hibernate 检索的成员 POJO 中的 CalendarFeed 列表中提取此信息。以下是简化的 POJO:

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;
}

目前,我有一个名为 CalendarResource 的 Jersey 资源,它可以手动输出带有日历提要信息的 JSON:

@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();
    }
}

但我不确定如何自动执行此操作。我刚刚开始使用 Jersey,不清楚如何使用它返回 JSON。听起来它有一种内置方法可以做到这一点,但看起来我需要向我的 POJO 添加注释。另外,我读到其他人说我需要使用杰克逊。我一直在谷歌搜索,似乎找不到从 Jersey 资源返回 JSON 的良好且简单的示例。有谁知道吗?或者您可以向我展示如何使用 Jackson 或 Jersey 为上面的示例创建 JSON 吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

热血少△年 2024-08-26 02:20:18

我想出了如何使用 Jackson 1.4 来做到这一点。我没有使用 jersey-json,因为它基于旧版本的 Jackson,并且我需要版本 1.4 才能使用 JsonViews。

这是带注释的 pojo:

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

这是球衣资源:

@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 "{}";
 }
}

这是我的 spring bean:

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

输出正是我需要的。使用 JsonViews,我可以自定义在不同情况下输出哪些字段。

希望这对其他人有帮助!

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!

吃素的狼 2024-08-26 02:20:18

自从编写了接受的答案以来,情况已经发生了变化。

如果打开 pojoMappingFeature,jersey 将自动调用 objectMapper。在 servlet 环境中,在您的球衣定义中执行以下操作:

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

您现在可以简单地从端点返回提要。

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

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();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文