使Jersey RESTful服务器符合Ember Data和JSON API标准

3

我目前运行着一台服务器,用于提供这样的数据:

单个实体

{"id":"11","name":"hello",....}

实体列表

[{single entity format},{},...]

然而,Ember Data 期望数据遵循JSON API规范的格式。
{"entity":{"id":"11","name":"hello",....}} OR {"entities":[{},{},{}...]}

否则它会返回错误:

Your server returned a hash with the key 0 but you have no mapping for it

我目前有一个responseFactory,它将构建响应作为一个映射,其中键是Ember模型(“users”/“user”)实体/列表,值是列表/实体本身。

是否有更好/更清晰的方法?

2个回答

3

我也在尝试正确配置Jackson以与Ember一起使用。请参见https://dev59.com/-WMl5IYBdhLWcg3wJD9S - miguelcobain

1
在您的情况下,请尝试像这样使用类:

import java.util.ArrayList;
import java.util.HashMap;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonRootName;

@JsonRootName("entity")
public class Entity {
   @JsonProperty
   public ArrayList<HashMap> entity = new ArrayList<HashMap>(); 

   public Entity() {    }

   public User(HashMap<String,Object> fields) {
      entity.add(fields);
   }
}

并且产生如下结果:

@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Entity producePost(Object object) {
    HashMap<String, Object> f = new HashMap<String,Object>();
    f.put("id", "11");
    f.put("name", "hello...");
    return new Entity(f);
}

它允许以Ember能够接受的格式进行生成,如下所示。
 {
  "entity" : [ {
    "id" : "11",
    "name" : "hello...."
  } ]
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接