简体   繁体   中英

How to convert Java object to Json object and put in json array

I want to do a ajax call on a button click. This will fetch records from mysql and will put in employee object. Now i want to send the employee object array kind of thing back to my ajax call. So thought of using JSON. package com;This code is working fine but i am unable to use Employee class and its object.Here i directly used JSON and its working.

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;
    }
}

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