简体   繁体   中英

Play Framework : JSON

I am not getting the JSON response I need, so it is difficult to use it through 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 :

{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

I believe you need to try to add the @SerializedName() annotation to your "salsum" class like so:

@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/

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 :

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

Thanks and Regards,

Nirav

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM