首页 > 解决方案 > 获取没有字符串名称的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"
}]

标签: androidarraysjsonrest

解决方案


尝试使用空字符串键

所以更换

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

推荐阅读