TMDb の API を使ってTV作品情報(JSON形式)を取得するお勉強 その2

前回より
TMDb の API を使ってTV作品情報(JSON形式)を取得するお勉強 その1 では、TMDb から TVドラマ情報を取得できた。しかし、取得した結果は System.Object に格納していたので、オブジェクト内のプロパティにアクセスするにはキー指定が必要だった。前回からの課題は「クラスから返却されるオブジェクトの構造を独自に定義する方法がわからない。」としていたけど、なんとなくできたかな。なんとなくなので、不適切かもしれないし、非効率かもしれない。また、App_Code に入れておくクラスではなく、DLL化してみた。

TMDb から TVドラマ情報を取得する .NET クラス を作成するお勉強

44歳、はじめてDLLを作成するので少しワクワク。

プロジェクトの作成

TMDb から TVドラマ情報を取得するクラス用プロジェクト「MJBTMDb」を作成。
01
JSONの逆デシリアライズには System.Web.Script.Serialization の JavaScriptSerializer を使用するが、System.Web.Extensions を参照設定で追加していなかったため、躓いた。
02

ソース

言語はVB。一部を掲載。

プロパティ

TVドラマ検索結果を格納するクラスを定義。複数の検索結果が返されることもあるので、1ドラマの結果 TvResult を List で複数格納できるようにした。こういう使い方でいいのだろうか?
TMDbTVSearch.vb
Imports Microsoft.VisualBasic
Imports System
Imports System.Collections.Generic
Imports System.Text
'-----------------------------------------------------------------------------------------------------------------
'TV
'-----------------------------------------------------------------------------------------------------------------
Namespace V3

    Public Class TvResult

        Public Property backdrop_path() As String
        Public Property id() As String
        Public Property original_name() As String
        Public Property first_air_date() As String
        Public Property origin_country() As List(Of String)
        Public Property poster_path() As String
        Public Property popularity() As Double
        Public Property name() As String
        Public Property vote_average() As Double
        Public Property vote_count() As Integer

    End Class

    Public Class TvResults

        Public Property page() As Integer
        Public Property TvResults() As List(Of TvResult)
        Public Property total_pages() As Integer
        Public Property total_results() As Integer

    End Class

End Namespace

TVドラマの作品基本情報クラス。
TMDbTVBase.vb
Imports Microsoft.VisualBasic
'-----------------------------------------------------------------------------------------------------------------
'TV
'-----------------------------------------------------------------------------------------------------------------
Namespace V3

    Public Class TMDbTVBase
        Public Property backdrop_path() As String
        Public Property created_by() As List(Of TvCreatedBy)
        Public Property episode_run_time() As List(Of Integer)
        Public Property first_air_date() As String
        Public Property genres() As List(Of MovieGenre)
        Public Property homepage() As String
        Public Property id() As Integer
        Public Property in_production() As Boolean
        Public Property languages() As List(Of String)
        Public Property last_air_date() As String
        Public Property name() As String
        Public Property networks() As List(Of TvNetwork)
        Public Property number_of_episodes() As Integer
        Public Property number_of_seasons() As Integer
        Public Property original_name() As String
        Public Property origin_country() As List(Of String)
        Public Property overview() As String
        Public Property popularity() As Int64
        Public Property poster_path() As String
        Public Property seasons() As List(Of TvSeason)
        Public Property status() As String
        Public Property vote_average() As Int64
        Public Property vote_count() As Integer

    End Class

    Public Class TvCreatedBy

        Public Property id() As Integer
        Public Property name() As String
        Public Property profile_path() As String

    End Class

    Public Class TvNetwork
        Public Property id() As Integer
        Public Property name() As String
    End Class

    Public Class TvSeason

        Public Property air_date() As String
        Public Property id() As Integer
        Public Property poster_path() As String
        Public Property season_number() As Integer

    End Class

End Namespace

コンスタント

APIキー、API用検索URL、API用取得URL を Public Shared で定義。
TMDbConstance.vb
Imports Microsoft.VisualBasic

Namespace V3

    Public Class TMDbConstance

        Public Shared APIKey As String
        Public Shared TMDbTVSearchURL As String
        Public Shared TMDbTVAPIGetURL As String

    End Class

End Namespace

MovieJukeBox は Webアプリなので、Global.asax の Application_Start で コンスタンスとなるAPIキー、API用検索URL、API用取得URLを Web.config から取得し設定するようにした。
Global.asax
<%@ Application Language="VB" %>

<script runat="server">

    Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
        '
        MJBTMDb.V3.TMDbTV.SetTMDbConstance(ConfigurationManager.AppSettings("tmdbAPIKey"), ConfigurationManager.AppSettings("TMDbTVSearchURL"), ConfigurationManager.AppSettings("TMDbTVAPIGetURL"))
    End Sub
    
    Sub Application_End(ByVal sender As Object, ByVal e As EventArgs)
        '
    End Sub
        
    Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
        '
    End Sub

    Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
        '
    End Sub

    Sub Session_End(ByVal sender As Object, ByVal e As EventArgs)
        '  
        ' : Session_End Web.config  sessionstate
        ' InProc session  StateServer  
        ' SQLServer
    End Sub
       
</script>

メソッド

メソッドは TMDbTV クラスにまとめた。TVドラマをキーワード検索する SearchTMDbTVID は、TvResultsクラス で返却するようにした。ID から TVドラマの作品基本情報を取得する GetTMDbTV については、オブジェクト TMDbTVBaseクラス で返却するようにした。シーズン情報を取得する GetTMDbTVSeason と エピソード情報を取得する GetTMDbTVSeasonEpisode は クラスを定義していないので、System.Object で返却するまま。後でクラスを定義する。   
TMDbTV.vb
Imports System.Net
Imports System.Web.Script.Serialization
Imports System.Data
Imports Microsoft.VisualBasic
Imports System.Collections.Generic
Imports System.Text
'-----------------------------------------------------------------------------------------------------------------
'
'-----------------------------------------------------------------------------------------------------------------
Namespace V3

    Public Class TMDbTV

        '---------------------------------------------------------------------------------------------------------
        '
        '---------------------------------------------------------------------------------------------------------
        Public Shared Sub SetTMDbConstance(ByVal APIKey As String, ByVal TMDbTVSearchURL As String, ByVal TMDbTVAPIGetURL As String)

            TMDbConstance.APIKey = APIKey
            TMDbConstance.TMDbTVSearchURL = TMDbTVSearchURL
            TMDbConstance.TMDbTVAPIGetURL = TMDbTVAPIGetURL

        End Sub
        '---------------------------------------------------------------------------------------------------------
        'JSON
        '---------------------------------------------------------------------------------------------------------
        Public Shared Function GetTMDbJSON(ByVal TargetURL As String) As Object

            Dim objWeb As WebClient = New WebClient()
            Dim objSrializer As JavaScriptSerializer = New JavaScriptSerializer()
            Dim objEncode As Encoding = Encoding.UTF8
            Dim byteResult As Byte()
            byteResult = objWeb.DownloadData(TargetURL)
            Dim UT8byteResult As String = objEncode.GetString(byteResult)
            Dim Hash As Hashtable = objSrializer.Deserialize(Of Hashtable)(UT8byteResult)
            Dim objresults As Object = Hash
            Return objresults

        End Function
        '---------------------------------------------------------------------------------------------------------
        'TV
        '---------------------------------------------------------------------------------------------------------
        Public Shared Function SearchTMDbTVID(ByVal Title As String, first_air_date_year As String, language As String) As TvResults

            Dim TargetUrl As String

            If first_air_date_year = "" Then
                TargetUrl = TMDbConstance.TMDbTVSearchURL + TMDbConstance.APIKey + "&query=" + Title + "&language=" + language
            Else
                TargetUrl = TMDbConstance.TMDbTVSearchURL + TMDbConstance.APIKey + "&query=" + Title + "&language=" + language + "&first_air_date_year=" + first_air_date_year
            End If

            'Return GetTMDbJSON(TargetUrl)

            Dim objTvResults As Object = GetTMDbJSON(TargetUrl)
            Dim TvResults As New TvResults()
            TvResults.page = objTvResults("page")
            TvResults.TvResults = TMDbAddList.SetTvResult(objTvResults("results"))
            TvResults.total_pages = objTvResults("total_pages")
            TvResults.total_results = objTvResults("total_results")

            Return TvResults

        End Function
        '---------------------------------------------------------------------------------------------------------
        'TV
        '---------------------------------------------------------------------------------------------------------
        Public Shared Function GetTMDbTV(ByVal TMDbTVID As String, language As String) As TMDbTVBase

            Dim TargetUrl As String = TMDbConstance.TMDbTVAPIGetURL + TMDbTVID + "?api_key=" + TMDbConstance.APIKey + "&language=" + language

            Dim objJSON As Object = GetTMDbJSON(TargetUrl)
            Dim objResults As Object = objJSON

            Dim objTMDb As New TMDbTVBase()

            objTMDb.backdrop_path = objResults("backdrop_path")
            objTMDb.created_by = TMDbAddList.Setcreated_by(objResults("created_by"))
            'episode_run_time
            Dim list_episode_run_time As New List(Of Integer)
            For Each item In objResults("episode_run_time")
                list_episode_run_time.Add(item)
            Next
            objTMDb.episode_run_time = list_episode_run_time
            objTMDb.first_air_date = objResults("first_air_date")
            'genres
            Dim listMovieGenre As New List(Of MovieGenre)
            For Each item In objResults("genres")
                Dim objgenres As New MovieGenre()
                objgenres.id = item("id")
                objgenres.name = item("name")
                listMovieGenre.Add(objgenres)
            Next
            objTMDb.genres = listMovieGenre
            objTMDb.homepage = objResults("homepage")
            objTMDb.id = objResults("id")
            objTMDb.in_production = objResults("in_production")
            objTMDb.languages = TMDbAddList.Setlanguages(objResults("languages"))
            objTMDb.last_air_date = objResults("last_air_date")
            objTMDb.name = objResults("name")
            objTMDb.networks = TMDbAddList.Setnetworks(objResults("networks"))
            objTMDb.number_of_episodes = objResults("number_of_episodes")
            objTMDb.number_of_seasons = objResults("number_of_seasons")
            objTMDb.original_name = objResults("original_name")
            objTMDb.origin_country = TMDbAddList.Setorigin_country(objResults("origin_country"))
            objTMDb.overview = objResults("overview")
            objTMDb.popularity = objResults("popularity")
            objTMDb.poster_path = objResults("poster_path")
            objTMDb.seasons = TMDbAddList.Setseasons(objResults("seasons"))
            objTMDb.status = objResults("status")
            objTMDb.vote_average = objResults("vote_average")
            objTMDb.vote_count = objResults("vote_count")

            Return objTMDb

        End Function
        '---------------------------------------------------------------------------------------------------------
        'TV
        '---------------------------------------------------------------------------------------------------------
        Public Shared Function GetTMDbTVSeason(ByVal TMDbTVID As String, SeasonNumber As String, language As String) As Object

            Dim TargetUrl As String = TMDbConstance.TMDbTVAPIGetURL + TMDbTVID + "/season/" + SeasonNumber + "?api_key=" + TMDbConstance.APIKey + "&language=" + language

            Return GetTMDbJSON(TargetUrl)

        End Function
        '---------------------------------------------------------------------------------------------------------
        'TV
        '---------------------------------------------------------------------------------------------------------
        Public Shared Function GetTMDbTVSeasonEpisode(ByVal TMDbTVID As String, SeasonNumber As String, EpisodeNumber As String, language As String) As Object

            Dim TargetUrl As String = TMDbConstance.TMDbTVAPIGetURL + TMDbTVID + "/season/" + SeasonNumber + "/episode/" + EpisodeNumber + "?api_key=" + TMDbConstance.APIKey + "&language=" + language

            Return GetTMDbJSON(TargetUrl)

        End Function

    End Class

End Namespace

JSON で受け取ったデータを一旦 System.Object に展開し、それをSystem.Collections.Generic 名前空間List(Of T) クラス で定義したリストへ展開するので、それ用のメソッドをまとめたクラス TMDbAddList を作った。
TMDbAddList.vb
Imports Microsoft.VisualBasic
'-----------------------------------------------------------------------------------------------------------------
'
'-----------------------------------------------------------------------------------------------------------------
Namespace V3

    Public Class TMDbAddList

        '---------------------------------------------------------------------------------------------------------
        'CreatedBy
        '---------------------------------------------------------------------------------------------------------
        Public Shared Function Setcreated_by(ByVal created_by As Object) As List(Of TvCreatedBy)

            Dim ListTvCreatedBy As New List(Of TvCreatedBy)
            For Each item In created_by
                Dim objTvCreatedBy As New TvCreatedBy()
                objTvCreatedBy.id = item("id")
                objTvCreatedBy.name = item("name")
                objTvCreatedBy.profile_path = item("profile_path")
                ListTvCreatedBy.Add(objTvCreatedBy)
            Next
            Return ListTvCreatedBy

        End Function
        '---------------------------------------------------------------------------------------------------------
        'languages
        '---------------------------------------------------------------------------------------------------------
        Public Shared Function Setlanguages(ByVal languages As Object) As List(Of String)

            Dim ListLanguage As New List(Of String)
            For Each item In languages
                ListLanguage.Add(item)
            Next
            Return ListLanguage

        End Function
        '---------------------------------------------------------------------------------------------------------
        'networks
        '---------------------------------------------------------------------------------------------------------
        Public Shared Function Setnetworks(ByVal created_by As Object) As List(Of TvNetwork)

            Dim ListTvNetwork As New List(Of TvNetwork)
            For Each item In created_by
                Dim objTvNetwork As New TvNetwork()
                objTvNetwork.id = item("id")
                objTvNetwork.name = item("name")
                ListTvNetwork.Add(objTvNetwork)
            Next
            Return ListTvNetwork

        End Function
        '---------------------------------------------------------------------------------------------------------
        'seasons
        '---------------------------------------------------------------------------------------------------------
        Public Shared Function Setseasons(ByVal seasons As Object) As List(Of TvSeason)

            Dim ListTvSeason As New List(Of TvSeason)
            For Each item In seasons
                Dim objTvSeason As New TvSeason()
                objTvSeason.id = item("id")
                objTvSeason.air_date = item("air_date")
                objTvSeason.poster_path = item("poster_path")
                objTvSeason.season_number = item("season_number")
                ListTvSeason.Add(objTvSeason)
            Next
            Return ListTvSeason

        End Function
        '---------------------------------------------------------------------------------------------------------
        'origin_country
        '---------------------------------------------------------------------------------------------------------
        Public Shared Function Setorigin_country(ByVal origin_country As Object) As List(Of String)

            Dim Listorigin_country As New List(Of String)
            For Each item In origin_country
                Listorigin_country.Add(item)
            Next
            Return Listorigin_country

        End Function
        '---------------------------------------------------------------------------------------------------------
        'TvResult
        '---------------------------------------------------------------------------------------------------------
        Public Shared Function SetTvResult(ByVal TvResults As Object) As List(Of TvResult)

            Dim ListTvResult As New List(Of TvResult)
            For Each item In TvResults
                Dim objTvResult As New TvResult()
                objTvResult.backdrop_path = item("backdrop_path")
                objTvResult.id = item("id")
                objTvResult.original_name = item("original_name")
                objTvResult.first_air_date = item("first_air_date")
                objTvResult.origin_country = TMDbAddList.Setorigin_country(item("origin_country"))
                objTvResult.poster_path = item("poster_path")
                objTvResult.popularity = item("popularity")
                objTvResult.name = item("name")
                objTvResult.vote_average = item("vote_average")
                objTvResult.vote_count = item("vote_count")
                ListTvResult.Add(objTvResult)
            Next
            Return ListTvResult

        End Function

    End Class

End Namespace

ビルドしてできた MJBTMDb.dll

メソッド
03
SearchTMDbTVID
04
SearchTMDbTVID の結果を格納するクラス。作品基本情報をリストで複数格納。
05
作品基本情報
06
適切に作れたか?は怪しいが、とりあえず MJBTMDb.dll で TMDb から 作品情報、シーズン情報、エピソード情報を取得できた。
タイトルを HEROES 、最初の公開年を 2006 で検索して、超能力ものの HEROES を選択。
07
作品情報
08
シーズン一覧が表示される。シーズン3を選択
09
シーズン3のエピソード一覧が表示される。
10

次回の課題

TMDb からは他にも、ポスター画像、ファンアート(backdrop)、youtube動画アドレス、キャスト、クルーが取得できるので、それらを取得できるように拡張する。

CodePlex への登録

みっともないかもしれないけど、できたら登録してみよう。やったことないけど。アドバイスとかもらえるのかな?あるいは適切に修正してくれるのかな?

コメント

このブログの人気の投稿

エアコン室外機のフロンガス銅管を覆うカバーを交換しました

ダブルクォーテーションで括られたCSVカ​ンマ区切りテキストファイルを SQL Server で Bulk Insert する方法

IKEAの鏡を壁に取り付ける