gpt4 book ai didi

android - (Android Volley) JSONObject 无法转换为 JSONArray

转载 作者:行者123 更新时间:2023-11-29 18:30:05 25 4
gpt4 key购买 nike

我在 android 中解析 JSON 数据时遇到问题。

我的安卓代码

JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, server_url,null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {

JSONArray jsonArray1=response.getJSONArray("employee");

for(int i=0;i<jsonArray1.length();i++)
{
JSONObject employe=jsonArray1.getJSONObject(i);

Log.d(TAG, "onResponse emp: "+employe.getString("name"));
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
}

我的 JSON 数据

{"orgs":[{"id":1551,"employeeId":1501,"orgId":"1151","employeeOrgMembershipStatus":"MEMBER","employeeRole":"SUPER_ADMIN","lMb":"alvin","lMd":"2019-06-01T05:41:00Z"}],"employee":{"id":1501,"employeeStatus":"ACTIVE","userId":"SU9iegDhr3b9r3gCUZzXl9eQjEJ2","name":"Alvin J Babu","cB":"alvin","cD":"2019-06-24T05:41:00Z","lMb":"alvin","lMd":"2019-06-27T05:41:00Z","computedTotalActivityScore":5,"stars":2,"jobTitle":"Developer","visibility":"ORGANIZATION","asset":null,"reportsTo":null},"teams":[{"id":1601,"employeeId":1501,"teamId":"1251","employeeTeamMembershipStatus":"MEMBER","lMb":"alvin","lMd":"2019-06-25T05:41:00Z"}],"status":1}

我需要解析员工数组并从中获取姓名。

最佳答案

首先使用像jsonprettyprint.com这样的网站轻松阅读 json。

这是您的 json,格式更易读:

{
"orgs": [
{
"id": 1551,
"employeeId": 1501,
"orgId": "1151",
"employeeOrgMembershipStatus": "MEMBER",
"employeeRole": "SUPER_ADMIN",
"lMb": "alvin",
"lMd": "2019-06-01T05:41:00Z"
}
],
"employee": {
"id": 1501,
"employeeStatus": "ACTIVE",
"userId": "SU9iegDhr3b9r3gCUZzXl9eQjEJ2",
"name": "Alvin J Babu",
"cB": "alvin",
"cD": "2019-06-24T05:41:00Z",
"lMb": "alvin",
"lMd": "2019-06-27T05:41:00Z",
"computedTotalActivityScore": 5,
"stars": 2,
"jobTitle": "Developer",
"visibility": "ORGANIZATION",
"asset": null,
"reportsTo": null
},
"teams": [
{
"id": 1601,
"employeeId": 1501,
"teamId": "1251",
"employeeTeamMembershipStatus": "MEMBER",
"lMb": "alvin",
"lMd": "2019-06-25T05:41:00Z"
}
],
"status": 1
}

在 JSON 中,任何受 {} 限制的都是 JSONObject,任何受 [] 限制的都是 JSONArray。

在您的情况下,正如您在上面的 JSON 中看到的那样,键“employee”具有 JSONObject 值,而不是您在代码中编写的 JSONArray。

在获得“employee”键的 JSONObject 后,您可以使用 employee.getString("name") 直接从中获取“name”字符串。

进行上述更改后的代码将如下所示:

public void onResponse(JSONObject response) {
try {
JSONObject employee=response.getJSONObject("employee");
String employeeName=employee.getString("name");
Log.d(TAG, "onResponse emp: "+employeeName);
}
catch (JSONException e) {
e.printStackTrace();
}
}

关于android - (Android Volley) JSONObject 无法转换为 JSONArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56760537/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com