Java 如何从 Jersey 资源生成 JSON?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2121390/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 03:45:33  来源:igfitidea点击:

How to generate JSON from a Jersey resource?

javajsonrestjerseyHymanson

提问by Tauren

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

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

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:

如果必须,我可以用 {"feeds": ... } 包围该 JSON,但最好将其设为可选。我想从存储在通过 Hibernate 检索的 Member 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;
}

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

目前,我有一个名为 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();
    }
}

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 Hymanson. 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 Hymanson or Jersey to create JSON for for the above example?

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

采纳答案by Tauren

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

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

Here is the annotated pojo:

这是带注释的 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:

这是我的春豆:

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

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

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

Hopefully this will help someone else!

希望这会帮助别人!

回答by case nelson

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:

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

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