How to convert cursor object to XML or JSON in android

Are there any libraries for converting a Cursor object to direct XML or JSON.

For example, we have a table with two columns id, name. When I get the cursor object from the DB. Using cursor cursor I want to convert it to

<XML>
<id>1<id>
<name>xyz</name>
</XML>

Thanks in advance.

+4
source share
2 answers

Use this:

JSONArray array = new JSONArray();
    if (cursor != null && cursor.getCount() > 0) {
        while (cursor.moveToNext()) {
            JSONObject object = new JSONObject();
            try {
                object.put("id", cursor.getString(0));
                object.put("name", cursor.getString(1));
                array.put(object);
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }

And if you want to create XML data, than use this: Link . Hope this helps you.

+2
source

Say I have a table called "people" with some data

id | name | Lastname

1 | john | Doe

2 | jane | Smith

and this is my simple code:

public String getRecords(String selectQuery){
    String recordSet = null;
    Cursor mCursor = database.rawQuery(selectQuery, null); 
    String[] colName = mCursor.getColumnNames();
   if (mCursor != null) {  

      recordSet = "{";
      mCursor.moveToFirst();

      do{
          StringBuilder sb = new StringBuilder();
          int columnsQty = mCursor.getColumnCount();
          for(int idx=0; idx<columnsQty; ++idx){
              sb.append(mCursor.getString(idx));
              if(idx<columnsQty-1){
                  sb.append(";");
              }
          }
          if(mCursor.getPosition()>0){
              recordSet +=",";
          }

          String row = formatRecords(colName, sb.toString());
          recordSet+= "\""+mCursor.getPosition()+"\":["+row+"]";

      }while(mCursor.moveToNext());

      recordSet += "}";

      return recordSet;


   }    
}
public String formatRecords(String[] colname, String rowData){
    String formatedData = null;
    String[] data = rowData.split(";");
    int colCount = colname.length;
    if(rowData !=null){
        formatedData = "{";
        for(int col=0; col<colCount; col++){
            if(col>0){
                formatedData += ", ";
            }
            formatedData += "\""+colname[col]+"\":\""+data[col]+"\"";
        }
        formatedData += "}";
    }
    Log.i(tag, formatedData);
    return formatedData

String data = getRecords("SELECT * FROM persons");

:

{"0":[{"id":"1","name":"john","lastname":"Doe"}],"1":[{"id":"2","name":"jane","lastname":"Smith"}]}

String .:) .

+1

Source: https://habr.com/ru/post/1539084/


All Articles