首页 > 解决方案 > 如何在gson对象模型类android中获取多少个键?

问题描述

我有一个如下所示的响应:

    "field_1":{
        
    },
    "field_2" : {
        "array_2": [
            {
                ... all other fields
            }
        ],
        "array_1": [
            {
               ... all other fields
            }
        ],
        // here will have 4 array or 5 array, I want to get how many array is inside this object
    },
    "field_3":{

    }

所以我让我的 POJO 类看起来像这样:

public class MyPojo{

    @SerializedName("field_1")
    @Expose
    private Field1 class1;


    @SerializedName("field_2")
    @Expose
    private Field2 class2;

    @SerializedName("field_3")
    @Expose
    private Field3 class3;

    // other getter and setter 
}

然后我会有一个Field2看起来像这样的类:

public class Entities {

    @SerializedName("array_1")
    @Expose
    private List<Array1Item> arraylist1 = null;
    @SerializedName("array_2")
    @Expose
    private List<Array2Item> arraylist2 = null;

    @SerializedName("array_3")
    @Expose
    private List<Array3Item> arraylist3 = null;

   //other getter setter

}

现在的问题是我想知道对象内部有多少个数组field_2。看起来我无法访问该field_2对象。

我尝试通过 访问它field2.names(),但无法解决。

因此,请有人帮忙。

我要的是array 1array 2里面有多少钥匙之类的field_2?它将返回一个值int。我怎样才能做到这一点?

标签: javaandroidjsongson

解决方案


尝试这个...

try {
    int total=0;
    JSONObject json = new JSONObject(field_2);
    Iterator<String> temp = json.keys();
    while (temp.hasNext()) {
        // do your other stuffs here
        total=total+1; //at last you will get total objects in field_2

    }
} catch (JSONException e) {
    e.printStackTrace();
}

或者

JSONObject object = new JSONObject (field_2_jsonObject);
JSONArray keys = object.names ();

//KEYS SIZE WILL YOUR TOTAL LENGTH IN "field_2"
for (int i = 0; i < keys.length (); i++) {
     String key = keys.getString (i); // Here's your key

 }

希望这会奏效...... :)


推荐阅读