0

How can i convert this json array to a json object. And i need to store this json to a remote server. How can i do it. I cannot find a perfect tutorial for this purpose.

 private JSONArray getResults() {
 String myPath = "/data/data/com.example.sebastian.patientdetails/databases/" + "MyDBName.db";
 String myTable = "patients";
 SQLiteDatabase myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
 String searchQuery = "SELECT * FROM " + myTable;
 Cursor cursor = myDataBase.rawQuery(searchQuery, null);
 JSONArray resultSet = new JSONArray();
 cursor.moveToFirst();
 while (!cursor.isAfterLast()) {
 int totalColumn = cursor.getColumnCount();
 JSONObject rowObject = new JSONObject();
 for (int i = 0; i < totalColumn; i++) {
 if (cursor.getColumnName(i) != null) {
 try {
 if (cursor.getString(i) != null) {
 Log.d("TAG_NAME", cursor.getString(i));
 rowObject.put(cursor.getColumnName(i), cursor.getString(i));
 } else {
 rowObject.put(cursor.getColumnName(i), "");
 }
 } catch (Exception e) {
 Log.d("TAG_NAME", e.getMessage());
 }
 }
 }
 resultSet.put(rowObject);
 cursor.moveToNext();
 }
 cursor.close();
 Log.d("TAG_NAME", resultSet.toString());
 return resultSet;
}
asked Oct 27, 2016 at 7:05
1
  • you can use rowObject.toString() and it will give you the string. Then you can send this string to remote server using network connection api Commented Oct 27, 2016 at 7:20

2 Answers 2

2
 while (!cursor.isAfterLast()) {
 int totalColumn = cursor.getColumnCount();
 JSONObject rowObject = new JSONObject();
 //new jsonarray
 JSONArray jsonArray=new JSONArray();
 for (int i = 0; i < totalColumn; i++) {
 if (cursor.getColumnName(i) != null) {
//new jsonarray of items jsonObject 
 JSONObject object = new JSONObject();
 try {
 if (cursor.getString(i) != null) {
 Log.d("TAG_NAME", cursor.getString(i));
 object.put(cursor.getColumnName(i),cursor.getString(i));
 } else {
 object .put(cursor.getColumnName(i), "");
 }
 //put jsonarray
 jsonArray.put(object );
 } catch (Exception e) {
 Log.d("TAG_NAME", e.getMessage());
 }
 }
 }
 //put request jsonobject
 rowObject.put(jsonArray);
 resultSet.put(rowObject);
 cursor.moveToNext();
}

you can use Google of Gson.jar,

answered Oct 27, 2016 at 7:42
Sign up to request clarification or add additional context in comments.

Comments

1

There is a method to convert json array into jsonObject,

JSONArray array;
for(int n = 0; n < array.length(); n++)
{
 JSONObject object = array.getJSONObject(n);
 //do what ever you want
}
answered Oct 27, 2016 at 7:11

1 Comment

I think you have to add this code after getting the Json array if your database is giving a JsonArray as response.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.