具有嵌套类的Jersey(JAX-RS 2.0)

时间:2014-08-08 16:19:14

标签: jersey jax-rs jersey-2.0

如何强制Jersey为嵌套类生成JSON输出,如下例所示?

当我使用Listing实例创建服务器发送的OutboundEvent时,Listing是一个嵌套类,不会产生JSON输出。

一旦我将列表重构为一个单独的外部类,一切正常。

public class Listings {

    private List<Listing> listings;

    public class Listing {

       private String name;

       public String getName() {
           return name;
       }


       public void setName(String name) {
           this.name = name;
       }

    }

    public List() {
        listings = new ArrayList<>();
    }

    public List<Listing> getListings() {
        return listings;
    }

    public void settListings(List<Listing> listings) {
        this.listings = listings;
    }

}

以下是创建JSON SSE的代码:

@GET
@Path("events")
@Produces(SseFeature.SERVER_SENT_EVENTS)
public EventOutput listingEvents() {
    final EventOutput eventOutput = new EventOutput();
    try {
        final OutboundEvent.Builder eventBuilder = new OutboundEvent.Builder();
        eventBuilder.mediaType(MediaType.APPLICATION_JSON_TYPE);
        eventBuilder.data(listings);  // of type Listings
        final OutboundEvent event = eventBuilder.build();
        eventOutput.write(event);
    } catch (IOException e) {
        throw new RuntimeException("Error when writing the event.", e);
    } finally {
        try {
            eventOutput.close();
        } catch (IOException ioClose) {
            throw new RuntimeException("Error when closing the event output.", ioClose);
        }
    }
    return eventOutput;
}

0 个答案:

没有答案