2013-11-16 3 views
0

У меня есть файл JSON, который я извлекаю из Интернета, который содержит данные расписания для телеканала. Вложенные в этом файле, наряду с большим количеством метаданных, является информация о каждом трансляции (т.е. каждая программа) и ниже приведен пример этого файла:Создание списка из вложенного JSON

For ease of understanding, I recommend this visual representation of the below JSON instead (click on the Viewer tab on the JSON viewer).

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

Использование the answer to this question on StackOverflow, я создал бина класс следующим образом:

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

ответ

0

1) Определить корень Json обертка класса ScheduleData.java

public class ScheduleData { 
    private Schedule schedule; 

    public Schedule getSchedule() { 
     return schedule; 
    } 
} 

2) Определите свои свойства как отдельные общественные классы:

2.а)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)собственности.Java

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

3) Определить AsyncTask и вызвать JSon службу. Получите результат как поток и установите его значение в экземпляр ScheduleData, используя gson library. (Я предполагаю, что вы знаете, как позвонить в службу 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 
+0

У меня возникли проблемы с работой моего адаптера просмотра списка. Это код в моей деятельности для вызова адаптера. Верно ли это? 'ListView listView = (ListView) findViewById (R.id.scheduleListView);' 'ScheduleListViewAdapter adapter = новый ScheduleListViewAdapter (это, R.layout.item_schedule_list, wideCastArr);' 'listView.setAdapter (адаптер);' – chivano

+0

Существует отметив это неправильно. (если ваш listView не является нулевым, и вы правильно применили ScheduleListViewAdapter) – Devrim

+0

Теперь он работает, спасибо! – chivano

Смежные вопросы