在不使用POJO类或仅使用1个POJO类的情况下,通过Restful服务发送ResultSet的Json

时间:2017-01-12 03:47:14

标签: json rest jersey jax-rs

我试图实现从PostgreSQL的ResultSet发送Json的restful服务,我能够通过使用Jersey将mapset映射到POJO类,我不想使用像Gson这样的任何其他库,但是我我希望在没有中间POJO的情况下直接将结果集作为Json发送,因为我不需要POJO用于​​任何其他目的,我对servlet或restfull或JAXB等不是很熟悉

我能够从ResultSet创建一个自定义的JsonArray(Javax.json)而没有POJO类,并转换为String并在服务上发送String,截至目前为数字,字符串,日期,时间戳(甚至可以尝试为数组做)使用递归,没有写自定义MessageBodyWriter,但可以编写简单的,甚至可能假装甚至为此写作)但是我并不完全理解我做的是否是正确的做法以及如何处理PostgreSQL到Json的所有数据类型并通过Rest发送。

请告诉我有关实施此方法的方法的建议,以及 请评论一些先进的事情,以及它们如何在Jersey,JAXB,JAX-RS上更清楚地相互关联,例如,就像POJO如何在内部转换为Json,哪个是转换的MessageBodyWriter。

请给我关于球衣的建议,而不是其他图书馆。

谢谢。

请找到我写的以下代码,并建议我改进。

资源类:

@Path("/message")
public class MessageResource {

    MessageService msgService = new MessageService();
    Test t = new Test();

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String getMessages() throws SQLException {
        return t.getAllMessages();
    }
}

服务类:

public class Test {

    private static ResultSetMetaData rsmd;
    private static int numOfColumns;
    PostgreHelper help = new PostgreHelper();
    public String getAllMessages() throws SQLException {

        RetrieveFromPostGre getData = new RetrieveFromPostGre();

        Map<String, ?> config = null;
        JsonBuilderFactory factory = Json.createBuilderFactory(config);
        JsonObjectBuilder rowJsonObject = factory.createObjectBuilder();
        JsonArrayBuilder tableJsonArray = factory.createArrayBuilder();

        getData.selectRows("db1", "schema1", "table1");
        ResultSet rs = getData.selectRows("db1", "schema1", "table1");
        rsmd=rs.getMetaData();  
        numOfColumns = rsmd.getColumnCount();
        try {
            while(rs.next()) { 
                createJsonObjectOfSingleRow(rs, rowJsonObject);
                tableJsonArray.add(rowJsonObject);
            }
        } catch (Exception e) {
            System.out.println("error");
        }
        return tableJsonArray.build().toString();
    }

    public void createJsonObjectOfSingleRow(ResultSet rs, JsonObjectBuilder rowJsonObject) throws SQLException {

        String numberType[] = {"BOOLEAN", "INTEGER", "FLOAT", "LONG", "DOUBLE"};
        String stringType[] = {"STRING", "DATE"};

        for (int i=1; i<=numOfColumns; i++) {                    

            String column_name = rsmd.getColumnName(i);
            System.out.println(help.getDataType(rsmd.getColumnType(i)));
            if(Arrays.asList(numberType).contains(help.getDataType(rsmd.getColumnType(i)))) {
                System.out.println("in num");
                rowJsonObject.add(column_name, rs.getInt(column_name));
            }
            else if(Arrays.asList(stringType).contains(help.getDataType(rsmd.getColumnType(i)))) {
                System.out.println("in stri");
                rowJsonObject.add(column_name, rs.getString(column_name));
            }
            else if(help.getDataType(rsmd.getColumnType(i)).equalsIgnoreCase("ARRAY")) {
                /* This is not working, and here I was thinking of doing recursion*/
                //System.out.println("in arr");
                //JsonArray jArray = (JsonArray) rs.getArray(column_name);
                //rowJsonObject.add(column_name, jArray);
                rowJsonObject.add("array", "flag");//just for the sake of running code successfully wrote this statement
            }
       }
    }
}

PostgreServices:

public class RetrieveFromPostGre {

    PostgreConnection postgreConnection = new PostgreConnection();
    PostgreHelper getColumnsMeta = new PostgreHelper();

    private String databaseName, schemaName, tableName;
    private Map<String, String> columns = new HashMap<String, String>();

    public String getDatabaseName() {
        return databaseName;
    }

    public void setDatabaseName(String databaseName) {
        this.databaseName = databaseName;
    }

    public String getSchemaName() {
        return schemaName;
    }

    public void setSchemaName(String schemaName) {
        this.schemaName = schemaName;
    }

    public String getTableName() {
        return tableName;
    }

    public void setTableName(String tableName) {
        this.tableName = tableName;
    }

    public Map<String, String> getColumns() {
        return columns;
    }

    public void setColumns(Map<String, String> columns) {
        this.columns = columns;
    }

    public ResultSet selectRows(String databaseName, String schemaName, String tableName) throws SQLException {

        this.setDatabaseName(databaseName);
        this.setSchemaName(schemaName);
        this.setTableName(tableName);

        Connection dbConnection = postgreConnection.getdbconnection(this.getDatabaseName());
        ResultSet rs = this.retrieveRows(dbConnection);

        return rs;
    }

    public ResultSet retrieveRows(Connection dbConnection) throws SQLException {

        Statement stmt = null;
        ResultSet rs = null;

        String sql;

        sql = "select * from " + this.schemaName + "." + this.tableName;

        try {
            stmt = dbConnection.createStatement();
            rs = stmt.executeQuery(sql);
            return rs;
            //stmt.close();
        } catch (Exception e) {
            System.err.println( e.getClass().getName()+": "+ e.getMessage() );
            e.printStackTrace();
            System.exit(0);
        }
        return rs;      
    }
}

DatabaseHelper:

public class PostgreHelper {

    public String getDataType(int i) {

        String type="";

        switch(i) {
            case java.sql.Types.INTEGER:  
                type="INTEGER";      break;
            case java.sql.Types.BIGINT:  
                type="LONG";      break;
            case java.sql.Types.BOOLEAN:  
                type="BOOLEAN";      break;
            case java.sql.Types.BIT:  
                type="BOOLEAN";      break;
            case java.sql.Types.FLOAT:   
                type="FLOAT";       break;
            case java.sql.Types.REAL:  
                type="DOUBLE";        break;
            case java.sql.Types.DOUBLE: 
                type="DOUBLE";      break;
            case java.sql.Types.NUMERIC:  
                type="INTEGER";     break;
            case java.sql.Types.DECIMAL:  
                type="DOUBLE";     break;
            case java.sql.Types.CHAR:  
                type="STRING";        break;
            case java.sql.Types.NCHAR:  
                type="STRING";        break;
            case java.sql.Types.VARCHAR:  
                type="STRING";    break;
            case java.sql.Types.NVARCHAR:  
                type="STRING";    break;
            case java.sql.Types.LONGVARCHAR: 
                type="STRING"; break;
            case java.sql.Types.DATE: 
                type="DATE";        break;
            case java.sql.Types.TIME: 
                type="DATE";        break;
            case java.sql.Types.TIMESTAMP: 
                type="DATE";   break;
            case java.sql.Types.BINARY:  
               type="BINARY";     break;
            case java.sql.Types.VARBINARY:  
                type="BINARY";  break;
            case java.sql.Types.LONGVARBINARY:   
                type="BINARY"; break;
            case java.sql.Types.NULL: 
                type="STRING";        break;
            case java.sql.Types.OTHER:  
                type="STRING";       break;
            case java.sql.Types.JAVA_OBJECT:  
                type="OBJECT"; break;
            case java.sql.Types.DISTINCT:  
                type="STRING";    break;
            case java.sql.Types.STRUCT:  
                type="STRING";      break;
            case java.sql.Types.ARRAY:  
                type="ARRAY";      break;
            case java.sql.Types.BLOB:  
                type="STRING";        break;
            case java.sql.Types.CLOB:  
                type="STRING";        break;
            case java.sql.Types.REF:  
                type="STRING";         break;
        } 

        return type;
    }
}

SerializableJSONArray Code,我写这个类代码只是为了知道评论者是否会工作:

public class SerializableJSONArray implements Serializable {
    private transient JSONArray jsonArray;

    public SerializableJSONArray(JSONArray jsonArray) {
        this.jsonArray = jsonArray;
    }

    public JSONArray getJSONArray() {
        return jsonArray;
    }

    private void writeObject(ObjectOutputStream oos) throws IOException {
        oos.defaultWriteObject();
        oos.writeObject(jsonArray.toString());
    }

    private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException, JSONException {
        ois.defaultReadObject();
        jsonArray = new JSONArray((String) ois.readObject());
    }
}

2 个答案:

答案 0 :(得分:0)

ResultSet不是serializable。你不能将它们直接转换(序列化)为json。

首先需要将ResultSet中所需的值提取到某个可序列化对象,然后再将其转换为json。

答案 1 :(得分:0)

将您的对象存储在地图中,然后将地图转换为json。

以下示例执行此操作,甚至不需要杰克逊。它使用javax.json

public static String toJSON(List<Map<String,String>> maps) {
  return javax.json.Json.createArrayBuilder(maps).build().toString();
}