Generate JSON from SQLite

1

I have a table with several records in SQLite , and also other data in SharedPreferences .

I would like to generate a JSON by pulling those records, and together that SharedPreferences data.

But in search, I barely found examples using only standard Android and Java (not GSON, etc.) classes as JSONObject and JSONArray .

For example:

SharedPreferences - 1 registro
Chave: usuario
Chave: token

SQLite - vários registros
Tabela: registros
Campos: id, usuario, anotacao

I wanted a JSON basically this way:

{
    "shared": [{
            "usuario": "fulano"
        },
        {
            "token": "xyz123"
        }
    ],

    "regs": [{
        "id": "10",
        "usuario": "1",
        "anotacao": "teste"
    }, {
        "id": "11",
        "usuario": "2",
        "anotacao": "teste 2"
    }]
}

I think I should connect to SQLite, create a cursor, cycle through the records and fields by adding each value, and then I can manually do one for SharedPreferences.

But the problem is this, I do not find examples! If you have links thank you.

    
asked by anonymous 23.02.2018 / 17:21

1 answer

1

You can do as you said. Create a thread, connect to SQLite, get all the data you need.

I think you can save everything in a hashmap to make it easier to transform into JSON. You can use Gson to transform from HashMap to JSON.

If you do not want to use Gson, then you kind of have to go recording field by field with JSONObject.

public static JSONObject quickParse(Object obj) throws IllegalArgumentException, IllegalAccessException, JSONException{
    JSONObject object = new JSONObject();

    Class<?> objClass = obj.getClass();
    Field[] fields = objClass.getDeclaredFields();
    for(Field field : fields) {
        field.setAccessible(true);
        Annotation[] annotations = field.getDeclaredAnnotations();
        for(Annotation annotation : annotations){
            if(annotation instanceof SerializedName){
               SerializedName myAnnotation = (SerializedName) annotation;
               String name = myAnnotation.value();
               Object value = field.get(obj);

               if(value == null)
                  value = new String("");

               object.put(name, value);
            }
        }
    }   

    return object;
}

This should return you a JSON object

    
27.02.2018 / 01:52