如何将复杂的JSON解析为ArrayAdapters

时间:2015-03-19 23:22:56

标签: java android json

我目前有一个JSON文件,我从服务器调用,如下所示:

{"owner":
    [{
        "username":"test-user",
        "email":"test-user@localhost",
        "id":1,"phone_number":"5555555555",
        "images":null,
        "pets":
            [{
                "id":4,
                "species":"Canine",
                "breed":"Labrador Retriever",
                "dob":{"date":"2015-03-19 11:03:24.000000","timezone_type":3,"timezone":"America\/Toronto"},
                "colour":"Gold",
                "pure_bred":"true"
            },
            {
                "id":3,
                "species":"Feline",
                "breed":"Persian",
                "dob":{"date":"2015-02-19 11:09:57.000000","timezone_type":3,"timezone":"America\/Toronto"},
                "colour":"Grey",
                "pure_bred":"false"
            }]
    }]
}

我的ArrayAdapter使用ArrayList可以很好地显示我的Owner实体。这正是我希望它看起来的样子,但是我无法正确提取我的Pets数据。因为宠物与ManyToOne实体有Owner的关系,我有时会得到不止一只宠物。不幸的是,似乎我只能为我的所有者显示一只宠物ArrayAdapter。有没有一种方法可以检索我的所有Pets实体并在单个LinearLayouts中显示它们以避免滚动问题?

我认为我走在正确的轨道上,但我根本不知道如何继续。

感谢。

ASyncTask

[...]

protected List<OwnerModel> doInBackground(String... params) {
    List<OwnerModel> result = new ArrayList<OwnerModel>();

    try {
        URL u = new URL(params[0]);
        HttpURLConnection conn = (HttpURLConnection) u.openConnection();
        conn.setRequestMethod("GET");

        conn.connect();
        InputStream is = conn.getInputStream();

        // Read the stream
        byte[] b = new byte[1024];
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        while (is.read(b) != -1)
            baos.write(b);

        String JSONResp = new String(baos.toByteArray());

        JSONObject jObj = new JSONObject(JSONResp);
        JSONArray arr = jObj.getJSONArray(ModelConstants.OWNER);

        for (int i = 0; i < arr.length(); i++) {
            result.add(convertHeader(arr.getJSONObject(i)));
        }
        return result;
    } catch (Throwable t) {
        t.printStackTrace();
    }

    return null;
}

private OwnerModel convertHeader(JSONObject obj) throws JSONException {
    // owner variables
    String id;
    String username;
    String email;
    String image;

    Owner om = new Owner();

    JSONArray petsArray = obj.getJSONArray(ModelConstants.PETS);
    if (!petsArray.getJSONObject(0).isNull("id")) {

        int modelInt = petsArray.length();

        // pet variables
        String pet_id;
        String pet_species;
        String pet_breed;
        String pet_pure_bred;
        String pet_colour;



        for (int i=0; i < modelInt; i++) {

            JSONObject petsJSONObj = petsArray.getJSONObject(i);
            pet_id = petsJSONObj.getString(ModelConstants.PET_ID);
            pet_species = petsJSONObj.getString(ModelConstants.PET_MANUFACTURER);
            pet_breed = petsJSONObj.getString(ModelConstants.PET_BREED);
            pet_pure_bred = petsJSONObj.getString(ModelConstants.PURE_BRED);
            pet_colour = petsJSONObj.getString(ModelConstants.PET_COLOUR);

            om.setPet_id(pet_id);
            om.setPet_species(pet_species);
            om.setPet_breed(pet_breed);
            om.setPet_model_year(pet_model_year);
            om.setPet_pure_bred(pet_pure_bred);
            om.setPet_colour(pet_colour);

        }
    }

    return om;
}

@Override
    protected void onPostExecute(List<OwnerModel> result) {
        if (result != null) {
            super.onPostExecute(result);
            ownerAdapter.setOwnerList(result);
            ownerAdapter.notifyDataSetChanged();

            petsAdapter.setOwnerList(result);
            petsAdapter.notifyDataSetChanged();
        }
    }

Activity
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my_profile);

    ownerAdapter = new OwnerAdapter(this, 0, new ArrayList<OwnerModel>());
    petsAdapter = new OwnerAdapter(this, 1, new ArrayList<OwnerModel>());
    header = (ListView) findViewById(R.id.myProfile_header);
    header.setAdapter(ownerAdapter);

    pets = (ListView) findViewById(R.id.listview_pets);
    pets.setAdapter(petsAdapter);

    (new FetchOwnerTask()).execute(HOST + "access_token=" + token.getAccessToken());
}

1 个答案:

答案 0 :(得分:1)

try {
        Object object = obj.opt(ModelConstants.PETS);
        if (object instanceof JSONArray) {
            ArrayList<Pet> petList = new ArrayList<Pet>();
            JSONArray msgList = (JSONArray) object;
            for (int i = 0; i < msgList.length(); i++) {
                Pet pet = new Pet();
                JSONObject petsJSONObj  = msgList.getJSONObject(i);
                String pet_id = petsJSONObj.getString(ModelConstants.PET_ID);
                pet.setPet_id(pet_id);
                String pet_species = petsJSONObj
                        .getString(ModelConstants.PET_MANUFACTURER);
                pet.setPet_species(pet_species);
                ......
                petList.add(pet);
            }
        }
        om.setPetList(petList);
    } catch (Exception e) {
        e.printStackTrace();
    }