(Android Volley) JSONObject не может быть преобразован в JSONArray - PullRequest
1 голос
/ 25 июня 2019

У меня была проблема с анализом данных JSON в Android.

мой код Android

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}

Мне нужно проанализировать массив сотрудников и получить из него имя.

Ответы [ 2 ]

1 голос
/ 25 июня 2019

Во-первых, используйте такие сайты, как 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, как вы написали в своем коде.

После того, как вы получите JSONObject ключа сотрудника, вы можете напрямую получить из него строку «name», используя employee.getString("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();
    }
}
1 голос
/ 25 июня 2019

Вот ваша модель

-----------------------------------com.example.Employee.java-----------------------------------

            package com.example;

            import com.google.gson.annotations.Expose;
            import com.google.gson.annotations.SerializedName;

    public class Employee {

        @SerializedName("id")
        @Expose
        private Integer id;
        @SerializedName("employeeStatus")
        @Expose
        private String employeeStatus;
        @SerializedName("userId")
        @Expose
        private String userId;
        @SerializedName("name")
        @Expose
        private String name;
        @SerializedName("cB")
        @Expose
        private String cB;
        @SerializedName("cD")
        @Expose
        private String cD;
        @SerializedName("lMb")
        @Expose
        private String lMb;
        @SerializedName("lMd")
        @Expose
        private String lMd;
        @SerializedName("computedTotalActivityScore")
        @Expose
        private Integer computedTotalActivityScore;
        @SerializedName("stars")
        @Expose
        private Integer stars;
        @SerializedName("jobTitle")
        @Expose
        private String jobTitle;
        @SerializedName("visibility")
        @Expose
        private String visibility;
        @SerializedName("asset")
        @Expose
        private Object asset;
        @SerializedName("reportsTo")
        @Expose
        private Object reportsTo;

        public Integer getId() {
            return id;
        }

        public void setId(Integer id) {
            this.id = id;
        }

        public String getEmployeeStatus() {
            return employeeStatus;
        }

        public void setEmployeeStatus(String employeeStatus) {
            this.employeeStatus = employeeStatus;
        }

        public String getUserId() {
            return userId;
        }

        public void setUserId(String userId) {
            this.userId = userId;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getCB() {
            return cB;
        }

        public void setCB(String cB) {
            this.cB = cB;
        }

        public String getCD() {
            return cD;
        }

        public void setCD(String cD) {
            this.cD = cD;
        }

        public String getLMb() {
            return lMb;
        }

        public void setLMb(String lMb) {
            this.lMb = lMb;
        }

        public String getLMd() {
            return lMd;
        }

        public void setLMd(String lMd) {
            this.lMd = lMd;
        }

        public Integer getComputedTotalActivityScore() {
            return computedTotalActivityScore;
        }

        public void setComputedTotalActivityScore(Integer computedTotalActivityScore) {
            this.computedTotalActivityScore = computedTotalActivityScore;
        }

        public Integer getStars() {
            return stars;
        }

        public void setStars(Integer stars) {
            this.stars = stars;
        }

        public String getJobTitle() {
            return jobTitle;
        }

        public void setJobTitle(String jobTitle) {
            this.jobTitle = jobTitle;
        }

        public String getVisibility() {
            return visibility;
        }

        public void setVisibility(String visibility) {
            this.visibility = visibility;
        }

        public Object getAsset() {
            return asset;
        }

        public void setAsset(Object asset) {
            this.asset = asset;
        }

        public Object getReportsTo() {
            return reportsTo;
        }

        public void setReportsTo(Object reportsTo) {
            this.reportsTo = reportsTo;
        }

    }
    -----------------------------------com.example.Example.java-----------------------------------

            package com.example;

            import java.util.List;
            import com.google.gson.annotations.Expose;
            import com.google.gson.annotations.SerializedName;

    public class Example {

        @SerializedName("orgs")
        @Expose
        private List<Org> orgs = null;
        @SerializedName("employee")
        @Expose
        private Employee employee;
        @SerializedName("teams")
        @Expose
        private List<Team> teams = null;
        @SerializedName("status")
        @Expose
        private Integer status;

        public List<Org> getOrgs() {
            return orgs;
        }

        public void setOrgs(List<Org> orgs) {
            this.orgs = orgs;
        }

        public Employee getEmployee() {
            return employee;
        }

        public void setEmployee(Employee employee) {
            this.employee = employee;
        }

        public List<Team> getTeams() {
            return teams;
        }

        public void setTeams(List<Team> teams) {
            this.teams = teams;
        }

        public Integer getStatus() {
            return status;
        }

        public void setStatus(Integer status) {
            this.status = status;
        }

    }
    -----------------------------------com.example.Org.java-----------------------------------

            package com.example;

            import com.google.gson.annotations.Expose;
            import com.google.gson.annotations.SerializedName;

    public class Org {

        @SerializedName("id")
        @Expose
        private Integer id;
        @SerializedName("employeeId")
        @Expose
        private Integer employeeId;
        @SerializedName("orgId")
        @Expose
        private String orgId;
        @SerializedName("employeeOrgMembershipStatus")
        @Expose
        private String employeeOrgMembershipStatus;
        @SerializedName("employeeRole")
        @Expose
        private String employeeRole;
        @SerializedName("lMb")
        @Expose
        private String lMb;
        @SerializedName("lMd")
        @Expose
        private String lMd;

        public Integer getId() {
            return id;
        }

        public void setId(Integer id) {
            this.id = id;
        }

        public Integer getEmployeeId() {
            return employeeId;
        }

        public void setEmployeeId(Integer employeeId) {
            this.employeeId = employeeId;
        }

        public String getOrgId() {
            return orgId;
        }

        public void setOrgId(String orgId) {
            this.orgId = orgId;
        }

        public String getEmployeeOrgMembershipStatus() {
            return employeeOrgMembershipStatus;
        }

        public void setEmployeeOrgMembershipStatus(String employeeOrgMembershipStatus) {
            this.employeeOrgMembershipStatus = employeeOrgMembershipStatus;
        }

        public String getEmployeeRole() {
            return employeeRole;
        }

        public void setEmployeeRole(String employeeRole) {
            this.employeeRole = employeeRole;
        }

        public String getLMb() {
            return lMb;
        }

        public void setLMb(String lMb) {
            this.lMb = lMb;
        }

        public String getLMd() {
            return lMd;
        }

        public void setLMd(String lMd) {
            this.lMd = lMd;
        }

    }
    -----------------------------------com.example.Team.java-----------------------------------

            package com.example;

            import com.google.gson.annotations.Expose;
            import com.google.gson.annotations.SerializedName;

    public class Team {

        @SerializedName("id")
        @Expose
        private Integer id;
        @SerializedName("employeeId")
        @Expose
        private Integer employeeId;
        @SerializedName("teamId")
        @Expose
        private String teamId;
        @SerializedName("employeeTeamMembershipStatus")
        @Expose
        private String employeeTeamMembershipStatus;
        @SerializedName("lMb")
        @Expose
        private String lMb;
        @SerializedName("lMd")
        @Expose
        private String lMd;

        public Integer getId() {
            return id;
        }

        public void setId(Integer id) {
            this.id = id;
        }

        public Integer getEmployeeId() {
            return employeeId;
        }

        public void setEmployeeId(Integer employeeId) {
            this.employeeId = employeeId;
        }

        public String getTeamId() {
            return teamId;
        }

        public void setTeamId(String teamId) {
            this.teamId = teamId;
        }

        public String getEmployeeTeamMembershipStatus() {
            return employeeTeamMembershipStatus;
        }

        public void setEmployeeTeamMembershipStatus(String employeeTeamMembershipStatus) {
            this.employeeTeamMembershipStatus = employeeTeamMembershipStatus;
        }

        public String getLMb() {
            return lMb;
        }

        public void setLMb(String lMb) {
            this.lMb = lMb;
        }

        public String getLMd() {
            return lMd;
        }

        public void setLMd(String lMd) {
            this.lMd = lMd;
        }

    }

Вы можете использовать этот сайт для создания моделей из ответа JSON

http://www.jsonschema2pojo.org/

...