0

I'm trying to format my sqlite data from all my columns into a JSONArray.

My sqlite data example is as follows:

id | name | product |
  
 1 | stev |[{"id":"1","title":"box"}] 

 1 | Lian |[{"id":"2","title":"bag"}] 
 
 1 | beny |[{"id":"3","title":"pen"}] 

I am saving a JSONArray as a string in my database under the column product.

I am trying to create a jsonArray using gson library.

This is what i have tried:

public String composeJSONfromSQLite() {

        ArrayList<HashMap<String, String>> offlineList;
        offlineList = new ArrayList<HashMap<String, String>>();
        String selectQuery = "SELECT  * FROM manyofflineCheckouts ";
  
        SQLiteDatabase database = this.getWritableDatabase();
        Cursor cursor = database.rawQuery(selectQuery, null);
  
        if (cursor.moveToFirst()) {
            do {
                HashMap<String, String> map = new HashMap<String, String>();
              map.put( cursor.getString(0));
              map.put( cursor.getString(1));
              map.put( cursor.getString(2));
              offlineList.add(map);

            } while (cursor.moveToNext());
        }
        database.close();

        Gson gson = new GsonBuilder().create();

        //Use GSON to serialize Array List to JSON

        return gson.toJson(offlineList);
    }

This however gives me in the format of:

[
	{
    	"id":"1",
    	"name":"stev",
    	"product":"[{"id":"1","title":"box"}]"
	},
	{
    	"id":"2",
    	"name":"Lian",
    	"product":"[{"id":"2","title":"bag"}]"
	}
]

This is not the correct Json format because of the double quotes surrounding product array "product":"[{"id":"1","title":"box"}]"

Is there a way to do this?

1
  • Are you saying you want the product value to be a JSON array instead of the string you see? Commented Apr 12, 2016 at 5:31

1 Answer 1

1

One way you can solve this is to parse your product json string first.

gson.fromJson(cursor.getString(2), Object[].class) instead of cursor.getString(2) will probably work in your case

Here is demo:

Gson gson = new GsonBuilder().create();

ArrayList<HashMap<String, Object>> offlineList = new ArrayList<>();

// here is what i'm taking about
String product = "[{\"id\":\"2\",\"title\":\"bag\"}]";
Object[] productObj = gson.fromJson(product, Object[].class)

HashMap<String, Object> map = new HashMap<>();
map.put("product", productObj );
map.put("id", 1);
map.put("name", "stev");
offlineList.add(map);

System.out.println(gson.toJson(offlineList));

Result:

[
  {
    "product": [
      {
        "id": "2",
        "title": "bag"
      }
    ],
    "id": 1,
    "name": "stev"
  }
]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.