2017-03-07 105 views
0

我想在点击按钮时做一个ajax调用。这将从MySQL获取记录,并将放入员工对象。现在我想将员工对象数组类发回我的ajax调用。所以想到使用JSON。 package com;此代码工作正常,但我无法使用Employee类和它的对象。在这里我直接使用JSON及其工作。如何将Java对象转换为Json对象并放入json数组

import java.sql.Connection; 
import java.sql.ResultSet; 
import java.sql.SQLException; 
import java.sql.Statement; 
import org.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 
public class SelectUsers { 
    public JSONArray selectQueryDemo() throws SQLException 
    { 
     GlobalConnection gc=new GlobalConnection(); 
     Connection conn=gc.getConnection(); 
     Statement s=conn.createStatement(); 
     ResultSet result=s.executeQuery("select * from tblemployees"); 
     String name = ""; 
     JSONArray jsonArray = new JSONArray(); 
     while(result.next()) 
     { 
      JSONObject obj = new JSONObject(); 
      try { 
       obj.put("id", result.getInt(1)); 
       obj.put("name", result.getString(2)); 
       obj.put("gender", result.getString(3)); 
      } catch (JSONException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
      jsonArray.put(obj); 
     } 
     return jsonArray; 
    } 
} 

回答

0

您应该可以通过使用Employee对象实例化JSon对象来完成它。

公共的JSONObject(对象豆)

使用豆吸气对象构建一个JSONObject。

你在Employee对象中有getter吗?