java - 如何在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 1
,array 2
里面有多少钥匙之类的field_2
?它将返回一个值int
。我怎样才能做到这一点?
解决方案
尝试这个...
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
}
希望这会奏效...... :)
推荐阅读
- chart.js - 使用 chart.js 和 moment.js 进行奇怪的时间格式化
- highcharts - 高图中样条系列的轮廓或边框
- linq - 如何将带有 switch 语句的 foreach 循环转换为 LINQ
- javascript - 用html写入另一个页面
- tfs - 在 visualstudio.com 上为 TFS 创建新管道
- python - 如果存在某个值,则解析 Json
- node.js - sequelize-typescript:模型中 get() 的常用方法
- ios - 具有未隐式定义的关联类型的通用协议
- javascript - 如何使用 MySQL 使用 ReactJS、NodeJS 登录?
- java - 在android中使用倒数计时器按钮