如何从Jersey资源生成JSON? [英] How to generate JSON from a Jersey resource?

查看:93
本文介绍了如何从Jersey资源生成JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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"
    }
]

如果必须,我可以用{包围JSON feed:...},但这是可选的最好。我想从CalendarFeeds列表中提取这些信息,这些CalendarFeeds存储在通过Hibernate检索的Member POJO中。以下是简化的POJO:

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

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

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

但我不确定如何进行自动化这个。我刚刚开始使用Jersey,并且不清楚如何使用它来返回JSON。听起来它有一种方法可以做到这一点,但看起来我需要为我的POJO添加注释。另外,我读了其他人说我需要使用杰克逊。我一直在谷歌搜索,似乎无法找到一个从Jersey资源返回JSON的简单例子。有人知道吗?或者你能告诉我如何使用Jackson或Jersey为上面的例子创建JSON吗?

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?

推荐答案

我想出了如何使用Jackson 1.4做到这一点。我没有使用jersey-json,因为它基于较旧版本的Jackson而且我需要1.4版才能使用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.

这是带注释的pojo:

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

这是球衣资源:

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

这是我的春豆:

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

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

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

希望这会帮助其他人!

这篇关于如何从Jersey资源生成JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆