Създаване на списъчен изглед от вложен JSON

Имам JSON файл, който извличам от интернет, който съдържа данни за график за телевизионен канал. В този файл, заедно с много метаданни, е вложена информация за всяко излъчване (т.е. всяка програма), а по-долу е извадка от този файл:

За по-лесно разбиране, Вместо това препоръчвам това визуално представяне на JSON по-долу (щракнете върху раздела Визуализатор в инструмента за преглед на JSON).

{
"schedule": {
    "service": {
      "type": "tv",
      "key": "bbcnews",
      "title": "BBC News Channel"
    },
    "day": {
      "date": "2013-11-15",
      "has_next": 1,
      "has_previous": 1,
      "broadcasts": [
        {
          "is_repeat": false,   <=== This is the 1st broadcast programme
          "is_blanked": false,
          "pid": "p01ks4z3",
          "start": "2013-11-15T03:45:00Z",
          "end": "2013-11-15T04:00:00Z",
          "duration": 900,
          "programme": {
            "type": "episode",
            "pid": "b03hdhhp",
            "position": null,
            "title": "15/11/2013",
            "short_synopsis": "All the latest sports news and results from around the globe.",
            "media_type": "audio_video",
            "duration": 900,
            "display_titles": {
              "title": "Sport Today",
              "subtitle": "15/11/2013"
            },
            "first_broadcast_date": "2013-11-15T03:45:00Z",
            "ownership": {
              "service": {
                "type": "tv",
                "id": "bbc_news24",
                "key": "bbcnews",
                "title": "BBC News Channel"
              }
            },
            "programme": {
              "type": "brand",
              "pid": "b0121xvw",
              "title": "Sport Today",
              "position": null,
              "expected_child_count": null,
              "first_broadcast_date": "2011-06-13T02:45:00+01:00",
              "ownership": {
                "service": {
                  "type": "tv",
                  "id": "bbc_news24",
                  "key": "bbcnews",
                  "title": "BBC News Channel"
                }
              }
            },
            "is_available_mediaset_pc_sd": false,
            "is_legacy_media": false
          }
        },
        {
          "is_repeat": false,  <=== This is the 2nd broadcast programme
          "is_blanked": false,
          "pid": "p01ks4z4",
          "start": "2013-11-15T04:00:00Z",
          "end": "2013-11-15T04:30:00Z",
          "duration": 1800,
          "programme": {
            "type": "episode",
            "pid": "b03hdhhs",
            "position": null,
            "title": "15/11/2013",
            "short_synopsis": "Twenty-four hours a day, the latest national and international stories as they break.",
            "media_type": "audio_video",
            "duration": 1800,
            "display_titles": {
              "title": "BBC News",
              "subtitle": "15/11/2013"
            },
            "first_broadcast_date": "2013-11-15T04:00:00Z",
            "ownership": {
              "service": {
                "type": "tv",
                "id": "bbc_news24",
                "key": "bbcnews",
                "title": "BBC News Channel"
              }
            },
            "programme": {
              "type": "brand",
              "pid": "b006mgyl",
              "title": "BBC News",
              "position": null,
              "expected_child_count": null,
              "first_broadcast_date": "2006-11-01T13:00:00Z",
              "ownership": {
                "service": {
                  "type": "tv",
                  "id": "bbc_news24",
                  "key": "bbcnews",
                  "title": "BBC News Channel"
                }
              }
            },
            "is_available_mediaset_pc_sd": false,
            "is_legacy_media": false
          }
        }
      ]
    }
  }
}

Използвайки отговора на този въпрос в StackOverflow, създадох такъв Javabean клас :

private class ScheduleData {

private Schedule schedule;
// create getter & setter

public static class Schedule {
    private Service service;
    private Day day;
    // create getter & setter
}

public static class Service {
    private String type;
    private String key;
    private String title;
    // create getter & setter
}

public static class Day {
    private String date;
    private String has_next;
    private String has_previous;
    private Broadcasts broadcasts;
    // create getter & setter
}

public static class Broadcasts {
    private String is_repeat;
    private String is_blanked;
    private String pid;
    private String time;
    private String end;
    private String duration;
    private OuterProgramme programme;
    // create getter & setter
}

public static class OuterProgramme {
    private String type;
    private String pid;
    private String position;
    private String title;
    private String short_synopsis;
    private String media_type;
    private String duration;    
    private String first_broadcast_date;
    private DisplayTitles display_titles;
    private Ownership ownership;
    private InnerProgramme programme;
    // create getter & setter  
}

public static class DisplayTitles {
    private String title;
    private String subtitle;
    // create getter & setter
}

public static class Ownership {
    private Service service;
    // create getter & setter
}

public static class Service {
    private String type;
    private String id;
    private String key;
    private String title;
    // create getter & setter
}

public static class InnerProgramme {
    private String type;
    private String pid;
    private String title;
    private String position;
    private String expected_child_count;
    private String first_broadcast_date;
    private Ownership ownership;
    private String is_available_mediaset_pc_sd;
    private String is_legacy_media;
    // create getter & setter
}
}

В моя файл за активност, как да превъртя всеки възел на излъчване на извлечения JSON и да извлека програмни данни като short_synopsis или display_titles и да ги предам в персонализиран дисплей за списък?


person chivano    schedule 16.11.2013    source източник


Отговори (1)


1) Дефинирайте коренния клас Json Wrapper ScheduleData.java

public class ScheduleData {
    private Schedule schedule;

    public Schedule getSchedule() {
        return schedule;
    }
}

2) Дефинирайте неговите свойства като отделни публични класове:

2.a) Schedule.java

public class Schedule {
    private Service service;
    private Day day;

    // TODO: create other getters & setters if you need
    public Day getDay() {
        return day;
    }
}

2.b) Service.java

public class Service {
    private String type;
    private String id;
    private String key;
    private String title;

    // TODO: create getters & setters if you need
}

2.c) Day.java

public class Day {
    private String date;
    private int has_next;
    private int has_previous;
    private Broadcast[] broadcasts;

    // TODO: create other getters & setters if you need
    public Broadcast[] getBroadcasts() {
        return broadcasts;
    }
}

2.d) Broadcast.java

public class Broadcast {
    private boolean is_repeat;
    private boolean is_blanked;
    private String pid;
    private String start;
    private String end;
    private int duration;
    private Programme programme;

    // TODO: create other getters & setters if you need
    public Programme getProgramme() {
        return programme;
    }
}

2.e) Programme.java

public class Programme {
    private String type;
    private String pid;
    private String position;
    private String title;
    private String short_synopsis;
    private String media_type;
    private int duration;
    private String first_broadcast_date;
    private DisplayTitle display_titles;
    private Ownership ownership;
    private Programme programme;

    // TODO: create other getters & setters if you need
    public String getShort_synopsis() {
        return short_synopsis;
    }

    public DisplayTitle getDisplay_titles() {
        return display_titles;
    }
}

2.f) DisplayTitle.java

public class DisplayTitle {
    private String title;
    private String subtitle;
    // create getter & setter
}

2.g) Ownership.java

public class Ownership {
    private Service service;
    // create getter & setter
}

3) Дефинирайте AsyncTask и извикайте json услуга. Получете резултат като поток и задайте стойността му на ScheduleData екземпляр с помощта на gson библиотека . (Предполагам, че знаете как да се обадите на услугата json на android, но ако не знаете, това е проблем с гугъл за 5 минути.)

HttpEntity getResponseEntity = getResponse.getEntity();
InputStream source = getResponseEntity.getContent();

Gson gson = new Gson();
Reader reader = new InputStreamReader(source);
ScheduleData scheduleData = gson.fromJson(reader, ScheduleData.class);

4) Сега имате екземпляр ScheduleData. Попълва се от json отговора на услугата.

Schedule schedule = scheduleData.getSchedule();
Day day = schedule.getDay();
Broadcast[] broadCastArr = day.getBroadcasts();
// TODO: use your broadCastArr in an adapter
person Devrim    schedule 16.11.2013
comment
Имам проблеми с работата на моя адаптер за изглед на списък. Това е кодът в моята дейност за извикване на адаптера. Правилно ли е? ListView listView = (ListView) findViewById(R.id.scheduleListView); ScheduleListViewAdapter adapter = new ScheduleListViewAdapter(this, R.layout.item_schedule_list, broadCastArr); listView.setAdapter(adapter); - person chivano; 16.11.2013
comment
В него има забележка. (ако вашият listView не е null и сте внедрили правилно ScheduleListViewAdapter) - person Devrim; 16.11.2013