0
所以我现在有一种丑陋的情况。我有一个包含“getAllData”方法的类版本。该方法返回InputStream的Supplier。在Java中使用供应商流<InputStream>给予泽西岛响应
public class Revision {
private String id;
private Supplier<InputStream> allData;
public Revision(String id, Supplier<InputStream> allData) {
this.id = id;
this.allData = allData;
}
public getAllData() {
return allData;
}
}
比方说,我有2个修订。他们宣称,像这样:
Supplier<InputStream> revisionValue1 =() -> new ByteArrayInputStream(
"{\"name\":\"George\", \"state\":\"Colorado\", \"Exp\":\"lots\"}".getBytes());
Revision revision1 = new Revision("Id1", revisionValue1);
Supplier<InputStream> revisionValue2 =() -> new ByteArrayInputStream(
"{\"name\":\"Sean\", \"state\":\"New York\"}".getBytes());
Revision revision2 = new Revision("Id2", revisionValue2);
而且他们放入地图成员:
Map<String, Revision> revisions = new HashMap<>();
revisions.put("Id1", revision1);
revisions.put("Id2", revision2);
电流的方法(这本身可能不是写得很好)返回流:
public Stream<Revision> getRevisions() {
return revisions.values().stream();
}
现在在我的Jersey代码中,我需要弄清楚如何将这些值作为Json格式的响应返回。所以结果应该是这样的:
[
{
"name": "George",
"state": "Colorado",
"Exp": "lots"
},
{
"name": "Sean",
"state": "New York"
}
]
我试图做到这一点,即使作为纯文本,这是行不通的。我想要的是:
@Produces(MediaType.TEXT_PLAIN)
public Response getRevisions(...) {
Stream<Revision> revisionObjects = getRevisions();
// each Revision option has a getAllData() method that needs called, which returns Supplier<InputStream>
// each Supplier<InputStream> contains, essentially, a Json record
// attempt at creating a StreamingOutput that can be sent as a response
if (revisionObjects != null) {
StreamingOutput stream = os -> {
Writer writer = new OutputStreamWriter(os);
Iterator<Revision> revisionIterator = revisionObjects.iterator();
while (revisionIterator.hasNext()) {
Revision next = revisionIterator.next();
writer.write(next.getAllData().get().toString());
}
writer.flush();
};
return Response.ok(stream).build();
}
return Response.noContent().build();
}
这是返回结果一样:
[email protected]@ba0b09
这我假设是因为有需要是“的toString()”方法之前一个额外的步骤作家。
对不起,这是多久,我只是想提供的细节。有谁知道如何让这个工作?理想情况下,我希望它能用JSON做出回应,但即使是纯文本也是一个巨大的进步。
P.S.我仍然试图围绕InputStreams和OutputStreams进行封装,所以很有可能,我有一些不合逻辑的东西。
“getAllData()”位于修订对象中,该对象是流中的单个元素。我将如何将getAllData()替换为查看调用它的单个修订版的东西? – user2869231
我编辑了这篇文章。这是你要求的吗? – Sanj
revisionResponse包含我想要的值,这非常棒。不过,我现在正在收到一个服务器错误,我认为它对于返回一个ArrayList作为响应感到愤怒。在回应中列出之前是否需要完成清单? – user2869231