游戏框架:JSON



我没有得到我需要的JSON响应,所以很难通过AngularJS使用它。下面是代码和所需的输出。

@Enity
@Table(name = "[empinfo]", schema = "[dbo]" )
public class salsum {
    public String location
        public String dept;
        public double salary;
}
public class salDAO{
    public static List<salsum> gsummary(){
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("defaultPersistenceUnit");
        EntityManager em = emf.createEntityManager();
        EntityTransaction txn = em.getTransaction();

            txn.begin();
            Query query =   em.createQuery("SELECT e.location, e.dept, e.salary FROM salsum e");

            List<salsum> salSum=  query.getResultList();

            txn.commit();
            return salSum;
    }
}
public class Application extends Controller {
    @Transactional
    public Result SalarySumJson()
    {
    //  return ok(Json.toJson(salDAO.gsummary()));
        Gson gson = new Gson();
        return ok(gson.toJson(salDAO.gsummary()));
    }
}

调用 DAO 后我得到输出:

{0: "Chicago", 1:"HR", 2: 20000}
{0: "Landon", 1:"HR", 2: 30000}
{0: "New York", 1:"HR", 2: 10000}

如何获得以下输出:

{"location": "Chicago",  "dept": "HR", "salary": 20000}
{"location": "Landon",   "dept": "HR", "salary": 30000}
{"location": "New York", "dept":"HR", "salary": 10000}

感谢和问候,

尼拉夫

我相信

您需要尝试将 @SerializedName() 注释添加到您的"salsum"类中,如下所示:

@Entity
@Table(name = "[empinfo]", schema = "[dbo]" )
public class salsum {
    @SerializedName("location")
    public String location;
    @SerializedName("dept")
    public String dept;
    @SerializedName("salary")
    public double salary;
}

希望这有帮助。有关更多信息,请参阅此处:

http://www.javacreed.com/gson-annotations-example/

问题

已解决。我在上面的代码中进行了以下更改:

在模型类中添加构造函数:

@Enity
@Table(name = "[empinfo]", schema = "[dbo]" )
public class salsum {
        public String location
        public String dept;
        public double salary;
        public salsum(String location, String dept, double salary)
        {this.location = location;
         this.dept = this.dept;
         this.salary = this.salary;
        }
}

并在查询中添加新的:

Query query =   em.createQuery("SELECT new salsum(e.location, e.dept, e.salary) FROM salsum e");

感谢和问候,

尼拉夫

最新更新