Tom Tom - 1 month ago 9
Android Question

Json array to object

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

Answer
 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,

Comments