如何使用GSON将Sqlite数据作为Json获取

时间:2016-04-12 05:07:28

标签: android json android-sqlite gson

我正在尝试将我的所有列中的sqlite数据格式化为JSONArray

我的sqlite数据示例如下:

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

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

我在JSONArray列下的数据库中将product保存为字符串。

我正在尝试使用jsonArray创建gson library

这就是我的尝试:

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);
    }

然而,这给了我以下格式:

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

这不是正确的Json格式,因为产品数组"product":"[{"id":"1","title":"box"}]"周围有双引号

有办法做到这一点吗?

1 个答案:

答案 0 :(得分:1)

解决此问题的一种方法是先解析product json字符串。

gson.fromJson(cursor.getString(2), Object[].class)代替cursor.getString(2)可能适用于您的情况

以下是演示:

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));

<强>结果:

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