Thursday, 21 April 2016

How to make ResultSet Object to JSON String in Java

package com.learners.converter;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.mysql.jdbc.jdbc2.optional.SuspendableXAConnection;

/**
 * @author jyotioeuvretc.com
 *
 */
public class Converter {

 /**
  * @param args
  */
 public static void main(String[] args) {
     try {
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://192.168.0.29/scylla","root","root");
PreparedStatement ps=con.prepareStatement("SELECT * FROM view_promocode_doctor ");
ResultSet rs=ps.executeQuery();
ResultSetMetaData rsm=rs.getMetaData();
System.out.println("col="+rsm.getColumnCount()+"table="+rsm.getTableName(1));
ArrayList<StringBuilder> collist=new ArrayList<StringBuilder>();
  
while(rs.next()){
StringBuilder sb=new StringBuilder();
sb.append("{");
for(int i=1;i<rsm.getColumnCount()+1;i++){ 
   
    //System.out.println(rsm.getColumnName(i)+":"+rs.getString(i)+",");
if(i==rsm.getColumnCount())
{
 sb.append("\""+rsm.getColumnName(i)+"\":\""+rs.getString(i)+"\"");
}
else
{
 sb.append("\""+rsm.getColumnName(i)+"\":\""+rs.getString(i)+"\",");
}
}
    
sb.append("}");
collist.add(sb);
}
//OutPut
 System.out.println(collist.toString());
  
 } catch (Exception e) {
  e.printStackTrace();
 }
     
     
  
 }

}
          


It give Output As....

 

No comments:

Post a Comment