我正在尝试将我的所有列中的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"}]"
周围有双引号
有办法做到这一点吗?
答案 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"
}
]