简体   繁体   中英

How to parse complicated JSON into ArrayAdapters

I currently have a JSON file that I'm calling from a server that looks like this:

{"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"
            }]
    }]
}

My ArrayAdapter using an ArrayList displays my Owner entity well. It's exactly how I want it to look, however I'm having trouble properly extracting my Pets data. Because the pets have a ManyToOne relationship with the Owner entity, I will sometimes get more than one pet. Unfortunately, it seems that I can only display one pet with my ArrayAdapter for my Owner. Is there a method to retrieve all of my Pets entities and display them in individual LinearLayouts to avoid scrolling issues?

I think I'm on the right track, but I simply don't know how to proceed.

Thanks.

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());
}
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();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM