解析没有键

时间:2018-03-13 07:58:54

标签: android json gson retrofit2

我正在尝试解析具有动态键值的远程json对象。这是我的 json格式

[
    {
        "Item": [
            {
                "Account": "Flowers",
                "Today": 1,
                "Tomorrow": 1
            }
        ]
    }
]

我无法在这里使用POJO类,因为远程json键始终是动态的。所以,我尝试使用Retrofit2下面的方法。

call.enqueue(new Callback<JsonElement>() {
            @Override
            public void onResponse(Call<JsonElement> call, Response<JsonElement> response) {

                Log.e("Here response is", response.body().toString() + " ");       // got "Here response is: [{"Item":[{"Account":"FLOWSERVE-FCD","Today":1,"Tomorrow":1}]}] "

                JsonArray responseArray= response.body().getAsJsonArray();

                try {
                    JsonObject jObj1 = (JsonObject) responseArray.get(0);
                    JsonArray jArray = jObj1.getAsJsonArray("Item");
                    JsonObject jObj2 = (JsonObject) jArray.get(0);

    // It is ok if we know the keys
    String value1 = jObj2.get("Account").toString();     // get FLOWSERVE-FCD
    String value2 = jObj2.get("Today").toString();      // get 1
    String value3 = jObj2.get("Tomorrow").toString();   // get 1

    // Here , I try for dynamic, but it got error
        ArrayList<String> dynamicKeys = new ArrayList<String>();   // create ArrayList to store dynamic keys later

                    for (int i = 0; i < jObj2.size(); i++) {
                        String str_image_url = jObj2.get(i);       //   although use "jObj2.keys(); it can't be used here.              
                        Log.e("Succcccc ", str_image_url);
                        dynamicKeys.add(str_image_url);
                    }



                } catch (Exception e) {
                    e.printStackTrace();
                    Log.e("Grrr Again", e.toString());
                }
            }

            @Override
            public void onFailure(Call<JsonElement> call, Throwable t) {
                Toast.makeText(context, t.getMessage(), Toast.LENGTH_LONG).show();
                Log.e("Grrr Error", t.getMessage());
            }
        });

如果我们知道 json键,它会很好用,但它会因动态键而困在我身上。所以,任何想法或替代方式都是欣赏的。

1 个答案:

答案 0 :(得分:1)

试试这个, 删除此代码

for (int i = 0; i < jObj2.size(); i++) {
                        String str_image_url = jObj2.get(i);       //   although use "jObj2.keys(); it can't be used here.              
                        Log.e("Succcccc ", str_image_url);
                        dynamicKeys.add(str_image_url);
                    }

替换为以下代码

 Set<Map.Entry<String, JsonElement>> entries = jObj2.entrySet();
                for (Map.Entry<String, JsonElement> entry : entries) {   
                    Log.e("Here keys", entry.getKey()); 
                    dynamicKeys.add(entry.getKey());
                    }