Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android Cursor to JSONArray

how can I "convert" a Cursor to a JSONArray?

my cursor as 3columns (_id, name, birth)

I've searched but I can't not find any examples

like image 752
Luis Neves Avatar asked Oct 25 '12 14:10

Luis Neves


People also ask

What is JsonResult?

What is JsonResult ? JsonResult is one of the type of MVC action result type which returns the data back to the view or the browser in the form of JSON (JavaScript Object notation format). In this article we will learn about JsonResult by taking scenario to bind view using the JSON Data .

Can you store JSON in MySQL?

MySQL supports the native JSON data type since version 5.7. 8. The native JSON data type allows you to store JSON documents more efficiently than the JSON text format in the previous versions. MySQL stores JSON documents in an internal format that allows quick read access to document elements.

How do I query a JSON column in MySQL?

How to Retrieve data from JSON column in MySQL. MySQL provides two operators ( -> and ->> ) to extract data from JSON columns. ->> will get the string value while -> will fetch value without quotes. As you can see ->> returns output as quoted strings, while -> returns values as they are.

What is column in JSON?

JSON columns, like columns of other binary types, are not indexed directly; instead, you can create an index on a generated column that extracts a scalar value from the JSON column. See Indexing a Generated Column to Provide a JSON Column Index, for a detailed example.


1 Answers

private String cursorToString(Cursor crs) {
    JSONArray arr = new JSONArray();
    crs.moveToFirst();
    while (!crs.isAfterLast()) {
        int nColumns = crs.getColumnCount();
        JSONObject row = new JSONObject();
        for (int i = 0 ; i < nColumns ; i++) {
            String colName = crs.getColumnName(i);
            if (colName != null) {
                String val = "";
                try {
                    switch (crs.getType(i)) {
                    case Cursor.FIELD_TYPE_BLOB   : row.put(colName, crs.getBlob(i).toString()); break;
                    case Cursor.FIELD_TYPE_FLOAT  : row.put(colName, crs.getDouble(i))         ; break;
                    case Cursor.FIELD_TYPE_INTEGER: row.put(colName, crs.getLong(i))           ; break;
                    case Cursor.FIELD_TYPE_NULL   : row.put(colName, null)                     ; break;
                    case Cursor.FIELD_TYPE_STRING : row.put(colName, crs.getString(i))         ; break;
                    }
                } catch (JSONException e) {
                }
            }
        }
        arr.put(row);
        if (!crs.moveToNext())
            break;
    }
    crs.close(); // close the cursor
    return arr.toString();
}
like image 170
grebulon Avatar answered Oct 30 '22 07:10

grebulon