android - 获取没有字符串名称的jsonarray
问题描述
我需要获取没有字符串名称的 json 数组:
代码选择 Sqlite:
public Cursor getAllData() {
String selectQuery = "Select * from capturas";
SQLiteDatabase db = new MyHelper(this).getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
return cursor;
}
代码 Json :
public JSONObject createJsonObject() throws JSONException {
Cursor cursor = getAllData();
JSONObject jobj;
JSONArray arr = new JSONArray();
cursor.moveToFirst();
while (cursor.moveToNext()) {
jobj = new JSONObject();
jobj.put("sCaptID", cursor.getString(0));
jobj.put("sName", cursor.getString(1));
arr.put(jobj);
}
jobj = new JSONObject();
jobj.put("data", arr);
return jobj;
}
我需要没有“数据”的jobj.put。
代码 JsonSend
public void postJsonToServer() throws JSONException {
JSONObject js = createJsonObject();
String url = "http://xx.1xx.xx9.xx/server";
JsonObjectRequest jsonObjReq = new JsonObjectRequest(com.android.volley.Request.Method.POST, url, js, new com.android.volley.Response.Listener<JSONObject>() {
结果json是:
{"data":[{
{
"id": "22",
"name": "test"
}]
}
我需要json结果:
[
{
"id": "22",
"name": "test"
}]
解决方案
尝试使用空字符串键
所以更换
jobj.put("data", arr);
和
jobj.put("", arr);
更新
结果是: {[{ { "id": "22", "name": "test" }] } ....--- 我需要 .....---[ { "id": "22 ", "名称": "测试" }]
现在尝试使用Google GSON 库来格式化您想要的 JSONObject,
将以下依赖项添加到 build.gradle 模块级别。
implementation 'com.google.code.gson:gson:2.8.5'
并将其更改createJsonObject()
为:
public JSONObject createJsonObject() throws JSONException {
Cursor cursor = getAllData();
JSONObject jobj;
JSONArray arr = new JSONArray();
cursor.moveToFirst();
while (cursor.moveToNext()) {
jobj = new JSONObject();
jobj.put("sCaptID", cursor.getString(0));
jobj.put("sName", cursor.getString(1));
arr.put(jobj);
}
Gson gson = new Gson();
String json = gson.toJson(arr, new TypeToken<JSONArray>() {
}.getType());
json = "{" + json + "}";
jobj = new JSONObject(json);
return jobj;
}
推荐阅读
- javascript - 找不到下一个 js 模块:无法解析“fs”
- google-cloud-pubsub - Q&A 没有出现在 pub sub 通知中
- html - 如何在平板电脑 Chrome 中隐藏自动完成框
- javascript - 无法读取未定义的属性(读取“显示”)
- javascript - 安装 ckeditor5 获取“意外令牌您可能需要适当的加载程序来处理此文件类型。” react.js 中的错误
- excel - VBA根据单元格值在另一个文件中设置数据透视表的新过滤器
- database - 创建图形界面
- go - opentelemetry-proto 导入路径和 AnyValue
- python - xpath selenium 找不到元素
- python - 列表对中的一个元素与其他元素