【问题标题】:Add name to array using jersey使用球衣将名称添加到数组
【发布时间】:2012-12-31 16:41:23
【问题描述】:

我正在实现一个例子here

我需要输出 json 来命名数组。

{"files":[]} 而不仅仅是{[]},这是我目前得到的输出。为数组添加名称需要做什么?

 @GET
 @Path("/{key}/meta")
public Response redirect(@PathParam("key") String key) throws IOException {
BlobKey blobKey = new BlobKey(key);
BlobInfo info = blobInfoFactory.loadBlobInfo(blobKey);

String name = info.getFilename();
long size = info.getSize();
String url = "/rest/file/" + key; 
FileMeta meta = new FileMeta(name, size, url);

List<FileMeta> metas = Lists.newArrayList(meta);
GenericEntity<List<FileMeta>> entity = new GenericEntity<List<FileMeta>>(metas) {};
return Response.ok(entity).build();

}

【问题讨论】:

    标签: java json jersey


    【解决方案1】:

    您需要您的实体类包含一个名为 filesList&lt;FileMeta&gt; 实例,才能获得该 JSON 输出。

    public Class EntityClass
    {
      private List<FileMeta> files;
      //Getter and Setter Methods.
    }
    

    这是您在 redirect 方法中需要具备的内容。

    @GET
    @Path("/{key}/meta")
    @Produces(MediaType.APPLICATION_JSON)
    public Response redirect(@PathParam("key") String key) throws IOException {
    BlobKey blobKey = new BlobKey(key);
    BlobInfo info = blobInfoFactory.loadBlobInfo(blobKey);
    
    String name = info.getFilename();
    long size = info.getSize();
    String url = "/rest/file/" + key; 
    FileMeta meta = new FileMeta(name, size, url);
    
    List<FileMeta> meta = Lists.newArrayList(meta);
    EntityClass entity= new EntityClass();
    entity.setFiles(meta);
    return Response.ok(entity).build();
    }
    

    PS:另外,你需要在你的 web.xml 中配置 POJOMapping。

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

    【讨论】:

    • 如果您遇到困难或我错过了一些细节,请告诉我。
    猜你喜欢
    • 1970-01-01
    • 2017-07-01
    • 2019-05-26
    • 1970-01-01
    • 2012-12-27
    • 1970-01-01
    • 2016-01-03
    • 2019-01-13
    • 1970-01-01
    相关资源
    最近更新 更多