Convert cursor To Json String - Android Database

Android examples for Database:Cursor Convert

Description

Convert cursor To Json String

Demo Code


//package com.java2s;
import android.database.Cursor;

public class Main {
    public static String cursorToJson(Cursor cursor) {
        StringBuilder builder = new StringBuilder();
        builder.append("{\"result\": [");
        boolean hasResult = false;
        while (cursor.moveToNext()) {
            hasResult = true;/*w  ww .jav a2  s.c  o  m*/
            int columnCount = cursor.getColumnCount();

            builder.append("{");
            for (int i = 0; i < columnCount; i++) {
                builder.append(
                        String.format("\"%s\": \"%s\"",
                                cursor.getColumnName(i),
                                cursor.getString(i))).append(",");
            }
            builder.deleteCharAt(builder.length() - 1);
            builder.append("},");
        }
        if (hasResult) {
            builder.deleteCharAt(builder.length() - 1);
        }
        builder.append("]}");
        cursor.close();
        return builder.toString();
    }
}

Related Tutorials