我有一个从服务器返回的信息列表,我将它放在名为“items”的arraylist中。我想知道如何只提取部门并将它们放入一个简单的字符串数组中,我将其命名为department list。
这就是列表的样子
[
{
"Department": "Mobile Development",
"Department": 22
},
{
" "Department": "IT Support",
"Department": 13
}]
这是我到目前为止编码的内容,但我认为我试图为每个添加的方式存在问题。
private void loadCompanyInfo() {
//final Context context = this.getActivity();
final Context context = this.context;
Organization client = new Organization(context);
Organization.api(context).getCompanyInforamtion(client.getID()).enqueue(new Callback<Results<CostCentresResult>>() {
@Override
public void onResponse(Call<Results<CostCentresResult>> call, Response<Results<CostCentresResult>> response) {
if (response.isSuccessful()) {
try {
Items = new ArrayList<>();
companyInfoList = new ArrayList<>();
Items.addAll(response.body());
if(Items.contains("Department")) {
Items.get(Items.indexOf(0));
for (int i = 0; i < Items.size(); i++) {
companyInfoList.add(Items[0])
}
}
} catch (Exception ex ) {
ex.printStackTrace();
ex.getMessage();
ex.getCause();
ex.getClass();
}
}
}
@Override
public void onFailure(Call<Results<CostCentresResult>> call, Throwable t) {
// TODO: handle ex
Errors.handleException(t);
}
});
}
}
答案 0 :(得分:0)
以下代码将帮助您从服务器响应中获取部门列表:
try {
ArrayList<String> mDepartmentList = new ArrayList<String>();
JSONArray serverResponseJsonArray = new JSONArray(response.body());
if (serverResponseJsonArray != null
&& serverResponseJsonArray.length() > 0) {
for (int i = 0; i < serverResponseJsonArray.length(); i++) {
JSONObject departmentJsonObj = serverResponseJsonArray
.getJSONObject(i);
if (departmentJsonObj != null
&& !departmentJsonObj.equals("")) {
if (departmentJsonObj.has("Department")) {
mDepartmentList.add(departmentJsonObj
.getString("Department"));
}
}
}
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}