Right now i'm working with SOAP UI and responce i get in ResultSet format. Since i preffer to work more with JSON rather then ResultSet, i found this nice solution that perfectly fits my needs.
Here's the code :
Thanks to this blog
Here's the code :
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.json.JSONArray; | |
import org.json.JSONObject; | |
import java.sql.ResultSet; | |
/** | |
* Utility for converting ResultSets into some Output formats | |
* @author marlonlom | |
*/ | |
public class Convertor { | |
/** | |
* Convert a result set into a JSON Array | |
* @param resultSet | |
* @return a JSONArray | |
* @throws Exception | |
*/ | |
public static JSONArray convertToJSON(ResultSet resultSet) | |
throws Exception { | |
JSONArray jsonArray = new JSONArray(); | |
while (resultSet.next()) { | |
int total_rows = resultSet.getMetaData().getColumnCount(); | |
JSONObject obj = new JSONObject(); | |
for (int i = 0; i < total_rows; i++) { | |
obj.put(resultSet.getMetaData().getColumnLabel(i + 1) | |
.toLowerCase(), resultSet.getObject(i + 1)); | |
jsonArray.put(obj); | |
} | |
} | |
return jsonArray; | |
} | |
/** | |
* Convert a result set into a XML List | |
* @param resultSet | |
* @return a XML String with list elements | |
* @throws Exception if something happens | |
*/ | |
public static String convertToXML(ResultSet resultSet) | |
throws Exception { | |
StringBuffer xmlArray = new StringBuffer("<results>"); | |
while (resultSet.next()) { | |
int total_rows = resultSet.getMetaData().getColumnCount(); | |
xmlArray.append("<result "); | |
for (int i = 0; i < total_rows; i++) { | |
xmlArray.append(" " + resultSet.getMetaData().getColumnLabel(i + 1) | |
.toLowerCase() + "='" + resultSet.getObject(i + 1) + "'"); } | |
xmlArray.append(" />"); | |
} | |
xmlArray.append("</results>"); | |
return xmlArray.toString(); | |
} | |
} |