0

I am trying parse only one json object, but the method only work if i have more than one element. In the JsonFactory class. I think it is a bug.

      public static ArrayList<Person> parseResult(String wsResponse) throws DataException {
                    ArrayList<Person> personList = new ArrayList<Person>();

                    try {
                        JSONObject parser = new JSONObject(wsResponse);
                        JSONObject jsonRoot = parser.getJSONObject(JSONTag.PERSON_LIST_ELEM_PEOPLE);
                        JSONArray jsonArray = jsonRoot
                                .getJSONArray(JSONTag.PERSON_LIST_ELEM_PERSON);
                        int size = jsonArray.length();
                        for (int i = 0; i < size; i++) {
                            JSONObject json = jsonArray.getJSONObject(i);
                            Person person = new Person();


                            person.name = json.getString(JSONTag.PERSON_LIST_ELEM_PERSON_NAME);



                            personList.add(person);
                        }
                    } catch (JSONException e) {
                        Log.e(TAG, "JSONException", e);
                        throw new DataException(e);
                    }

                    return personList;
                }

1 Answers1

1

The way to parse JSON depends on your JSON format. There are 2 patterns of JSON:

  • JSON Arrays:

    { "myarray" : [ {obj1}, {obj2}, {obj3}, ... ] ]

  • JSON Objects:

    { "myobject" : { field1:"", field2:"", ...} }

You just need to use the corresponding code for it. In the code you pasted I was expected a JSON array.

If you have only one object, just modify the code to only use one object. Some similar to:

JSONObject parser = new JSONObject(wsResponse);
JSONObject jsonRoot = parser.getJSONObject(JSONTag.PERSON_LIST_ELEM_PEOPLE);
JSONObject json = jsonRoot.getJSONObject(JSONTag.<<MY_OBJECT>>)

person.name = json.getString(JSONTag.PERSON_LIST_ELEM_PERSON_NAME);
Foxykeep
  • 218
  • 2
  • 6