如何将此json数组转换为json对象。我需要将这个json存储到远程服务器。我该怎么做。我找不到一个完美的教程用于此目的。
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;
}
答案 0 :(得分: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();
}
您可以使用Google的Gson.jar,
答案 1 :(得分:1)
有一种方法可以将json数组转换为jsonObject,
JSONArray array;
for(int n = 0; n < array.length(); n++)
{
JSONObject object = array.getJSONObject(n);
//do what ever you want
}