【问题标题】:Get jsonarray without string name获取不带字符串名称的jsonarray
【发布时间】:2020-09-08 12:37:34
【问题描述】:

我需要得到没有字符串名称的 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"
}]

【问题讨论】:

    标签: android arrays json rest


    【解决方案1】:

    尝试使用空字符串键

    所以替换

    jobj.put("data", arr);
    

    jobj.put("", arr);
    

    更新

    结果是:{[{ { "id": "22", "name": "test" }] } ....--- 我需要 .....---[ { "id" :“22”,“名称”:“测试”}]

    现在尝试使用Google GSON library 来格式化你想要的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;
    }
    

    【讨论】:

    • 结果是:{[{ { "id": "22", "name": "test" }] } ....--- 我需要..... [ { "id": "22", "name": "test" }]
    • @MexiCano 请在UPDATE 部分查看更新的答案
    【解决方案2】:
    return jobj.data
    

    而不是

    return jobj
    

    我认为这几乎可以解决您的请求,或者您可以使用 JSON.stringify 将其转换为字符串,然后使用 splice/slice 方法将多余部分切掉并使用 JSON.parse 将其转换回数组。但那将是奇怪

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-09
      • 1970-01-01
      • 2016-06-30
      • 1970-01-01
      • 1970-01-01
      • 2018-03-01
      • 2023-03-26
      • 2012-04-27
      相关资源
      最近更新 更多