[英]Play Framework : JSON
I am not getting the JSON response I need, so it is difficult to use it through AngularJS. 我没有得到所需的JSON响应,因此很难通过AngularJS使用它。 Below is the code and required output.
以下是代码和所需的输出。
@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()));
}
}
I am getting the output after calling DAO : 调用DAO后,我得到了输出:
{0: "Chicago", 1:"HR", 2: 20000}
{0: "Landon", 1:"HR", 2: 30000}
{0: "New York", 1:"HR", 2: 10000}
How can I get the below output : 我如何获得以下输出:
{"location": "Chicago", "dept": "HR", "salary": 20000}
{"location": "Landon", "dept": "HR", "salary": 30000}
{"location": "New York", "dept":"HR", "salary": 10000}
Thanks and Regards, 谢谢并恭祝安康,
Nirav Nirav
I believe you need to try to add the @SerializedName() annotation to your "salsum" class like so: 我相信您需要尝试将@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;
}
Hope this helps. 希望这可以帮助。 Please see this for more information:
请查看此以获取更多信息:
http://www.javacreed.com/gson-annotations-example/ http://www.javacreed.com/gson-annotations-example/
Problem is resolved. 问题已解决。 I have made following changes in above code :
我在上面的代码中做了以下更改:
Add constructor in model class : 在模型类中添加构造函数:
@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;
}
}
and in query add new : 并在查询中添加new:
Query query = em.createQuery("SELECT new salsum(e.location, e.dept, e.salary) FROM salsum e");
Thanks and Regards, 谢谢并恭祝安康,
Nirav Nirav
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.