Невозможно преобразовать JSON проанализированный ответ в массив - PullRequest
0 голосов
/ 17 марта 2020

Я использую API TMDb для получения данных для моей программы в VB и пытаюсь получить массив всех идентификаторов фильмов, возвращенных из необработанного ответа JSON, но он продолжает выдавать ошибку , мой код находится на VB. net, и мой код выглядит так:

Imports System.IO
Imports System.Net
Imports Newtonsoft.Json.Linq
Public Class TMDb_Connection

    Private API_Key As String = "my api key"
    Private API_url As String = "https://api.themoviedb.org/3"
    Private API_Image_Base_url As String = "https://image.tmdb.org/t/p/w500/"
    Private API_Pagination As String = "1"

    Public Sub SearchAPI(ByVal API_Query As String, ByVal ObjectToken As String)
        Dim Response As HttpWebResponse
        Dim postData As String = "api_key=" & API_Key & "&query=" & WebUtility.UrlEncode(API_Query) 
        Dim Request As HttpWebRequest = DirectCast(HttpWebRequest.Create(API_url & "/search/movie?" & postData), HttpWebRequest)
        Request.Method = "GET"

        Try
            Response = DirectCast(Request.GetResponse(), HttpWebResponse)
            Dim Stream As Stream = Response.GetResponseStream()
            Dim reader As New StreamReader(Stream, Encoding.GetEncoding("utf-8"))
            Dim responseFromServer As String = reader.ReadToEnd()
            reader.Close()
            Response.Close()
            Dim obj = JObject.Parse(responseFromServer)
            Dim obj2 As String = JObject.Parse(obj.SelectToken("results"))
            MsgBox(obj.SelectToken(ObjectToken))
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

End Class

, и вот необработанный ответ JSON, который я получаю от TMDb API. Вот ссылка на любую информацию об API, если необходимо.

{
  "page": 1,
  "total_results": 22,
  "total_pages": 2,
  "results": [
    {
      "popularity": 36.796,
      "vote_count": 18368,
      "video": false,
      "poster_path": "/4GpwvwDjgwiShr1UBJIn5fk1gwT.jpg",
      "id": 550,
      "adult": false,
      "backdrop_path": "/pCUdYAaarKqY2AAUtV6xXYO8UGY.jpg",
      "original_language": "en",
      "original_title": "Fight Club",
      "genre_ids": [
        18
      ],
      "title": "Fight Club",
      "vote_average": 8.4,
      "overview": "A ticking-time-bomb insomniac and a slippery soap salesman channel primal male aggression into a shocking new form of therapy. Their concept catches on, with underground \"fight clubs\" forming in every town, until an eccentric gets in the way and ignites an out-of-control spiral toward oblivion.",
      "release_date": "1999-10-15"
    },
    {
      "popularity": 5.124,
      "vote_count": 23,
      "video": false,
      "poster_path": "/iI9c8XNdPuwB4RYbHMd62QNhoRK.jpg",
      "id": 440777,
      "adult": false,
      "backdrop_path": "/qziKhMyrVqj567jlbj55GpBdKf9.jpg",
      "original_language": "en",
      "original_title": "Female Fight Club",
      "genre_ids": [
        28
      ],
      "title": "Female Fight Club",
      "vote_average": 5.4,
      "overview": "A former fighter reluctantly returns to the life she abandoned in order to help her sister survive the sadistic world of illegal fighting and the maniac who runs it.",
      "release_date": "2017-03-16"
    },
    {
      "popularity": 2.713,
      "vote_count": 0,
      "video": false,
      "poster_path": null,
      "id": 259016,
      "adult": false,
      "backdrop_path": null,
      "original_language": "en",
      "original_title": "Insane Fight Club",
      "genre_ids": [
        99
      ],
      "title": "Insane Fight Club",
      "vote_average": 0,
      "overview": "A group of friends have created a brand new subculture that is taking over the streets of Glasgow. They've established their very own fight club, but this is no ordinary wrestling event - this is brutal, riotous chaos. Fights don't always stay inside the ring, people are bounced off the side of buses and thrown off balconies in pubs. They now plan the biggest show of their lives. The stakes are high, will it bring them the fame and recognition they need to survive?",
      "release_date": "2014-03-11"
    },
    {
      "popularity": 1.864,
      "id": 466848,
      "video": false,
      "vote_count": 18,
      "vote_average": 7.1,
      "title": "Superhero Fight Club",
      "release_date": "2015-04-13",
      "original_language": "en",
      "original_title": "Superhero Fight Club",
      "genre_ids": [
        28,
        878
      ],
      "backdrop_path": "/u0a4CSy73GP11wVPz8hm0tHQwci.jpg",
      "adult": false,
      "overview": "Oliver introduces Barry to his own little fight club which features such members as Roy Harper, Laurel Lance, Malcolm Merlyn and Ra's Al Ghul.",
      "poster_path": "/zjPn7JUg2tsxlRWp4luK0YVX48Y.jpg"
    },
    {
      "popularity": 1.299,
      "vote_count": 8,
      "video": false,
      "poster_path": "/aXFmWfWYCCxQTkCn7K86RvDiMHZ.jpg",
      "id": 347807,
      "adult": false,
      "backdrop_path": null,
      "original_language": "hi",
      "original_title": "Fight Club: Members Only",
      "genre_ids": [
        28
      ],
      "title": "Fight Club: Members Only",
      "vote_average": 3.5,
      "overview": "Four friends head off to Bombay and get involved in the mother and father of all gang wars.",
      "release_date": "2006-02-17"
    },
    {
      "popularity": 1.264,
      "id": 104782,
      "video": false,
      "vote_count": 0,
      "vote_average": 0,
      "title": "Florence Fight Club",
      "release_date": "2010-01-01",
      "original_language": "en",
      "original_title": "Florence Fight Club",
      "genre_ids": [
        28,
        53
      ],
      "backdrop_path": null,
      "adult": false,
      "overview": "Four men decided to enter in the oldest Fight Club of the History, The Florentine Football tournament. A father and son, a black guy, an old champion and outsider clerk will enter in an arena of the time to win their fears, to go over their limits, to be heroes for a day.",
      "poster_path": null
    },
    {
      "popularity": 2.017,
      "vote_count": 19,
      "video": false,
      "poster_path": "/uvBmJX04cmOtpEHZmY2MBoAwuVn.jpg",
      "id": 289732,
      "adult": false,
      "backdrop_path": null,
      "original_language": "zh",
      "original_title": "Zombie Fight Club",
      "genre_ids": [
        28,
        27
      ],
      "title": "Zombie Fight Club",
      "vote_average": 3.5,
      "overview": "It's the end of the century at a corner of the city in a building riddled with crime - Everyone in the building has turned into zombies. After Jenny's boyfriend is killed in a zombie attack, she faces the challenge of surviving in the face of adversity. In order to stay alive, she struggles with Andy to flee danger.",
      "release_date": "2014-10-23"
    },
    {
      "popularity": 4.224,
      "vote_count": 0,
      "video": false,
      "poster_path": null,
      "id": 322772,
      "adult": false,
      "backdrop_path": null,
      "original_language": "en",
      "original_title": "Insane Fight Club II - This Time It’s Personal",
      "genre_ids": [
        99
      ],
      "title": "Insane Fight Club II - This Time It’s Personal",
      "vote_average": 0,
      "overview": "Insane Fight Club is back. This year the boys are taking their unique form of entertainment to England as they stage fight nights in Birmingham, Leeds, Liverpool and Newcastle.",
      "release_date": "2015-01-21"
    },
    {
      "popularity": 0.6,
      "id": 289100,
      "video": false,
      "vote_count": 0,
      "vote_average": 0,
      "title": "Girls Fight Club",
      "release_date": "2009-06-18",
      "original_language": "en",
      "original_title": "Girls Fight Club",
      "genre_ids": [],
      "backdrop_path": null,
      "adult": false,
      "overview": "The best women's wrestling competition of all time...and if you think it's fake you're in for a big surprise See LEGENDARY Mixed Martial Arts fighters coach their teams to victory in the cage! aka Chuck Lidell's Girl's Fight Club",
      "poster_path": null
    },
    {
      "popularity": 1.07,
      "vote_count": 5,
      "video": false,
      "poster_path": null,
      "id": 51021,
      "adult": false,
      "backdrop_path": null,
      "original_language": "en",
      "original_title": "Lure: Teen Fight Club",
      "genre_ids": [
        28,
        80,
        18
      ],
      "title": "Lure: Teen Fight Club",
      "vote_average": 3,
      "overview": "A community is under siege as three Belmont Highschool coed students go missing with no trace of their whereabouts. The pressure is on the police to capture the culprits responsible. Scouring the school hallways in search of clues, undercover female detective Maggie Rawdon (Jessica Sonnerborn) enters Belmont High as a transfer student in an attempt to solve the hideous disappearance of the students. Maggie makes a few new friends, and gets invited to a private rave in the country. Just as the group begins to suspect that they've taken a wrong turn, however, the trap is sprung and Maggie finds out firsthand what fate has befallen the missing girls.",
      "release_date": "2010-11-16"
    },
    {
      "popularity": 0.6,
      "vote_count": 3,
      "video": false,
      "poster_path": null,
      "id": 151912,
      "adult": false,
      "backdrop_path": null,
      "original_language": "en",
      "original_title": "Jurassic Fight Club",
      "genre_ids": [
        99
      ],
      "title": "Jurassic Fight Club",
      "vote_average": 6.7,
      "overview": "Jurassic Fight Club, a paleontology-based miniseries that ran for 12 episodes, depicts how prehistoric beasts hunted their prey, dissecting these battles and uncovering a predatory world far more calculated and complex than originally thought. It was hosted by George Blasing, a self-taught paleontologist.",
      "release_date": "2008-10-22"
    },
    {
      "popularity": 0.6,
      "id": 600819,
      "video": false,
      "vote_count": 0,
      "vote_average": 0,
      "title": "Fight Club: Des Moines",
      "release_date": "2018-03-04",
      "original_language": "en",
      "original_title": "Fight Club: Des Moines",
      "genre_ids": [],
      "backdrop_path": null,
      "adult": false,
      "overview": "What if Tyler Durden came to Des Moines, Iowa? This might be what it would look like.",
      "poster_path": null
    },
    {
      "popularity": 0.6,
      "id": 532155,
      "video": false,
      "vote_count": 1,
      "vote_average": 7,
      "title": "Musangwe: Fight Club",
      "release_date": "",
      "original_language": "en",
      "original_title": "Musangwe: Fight Club",
      "genre_ids": [],
      "backdrop_path": null,
      "adult": false,
      "overview": "The first rule is that there are no rules. For the bare-knuckle combatants competing in Musangwe fights, anything goes - you can even put a curse on him. The sport, which dates back centuries, has become a South African institution. Any male from the age of nine to ninety can compete. We follow a group of fighters as they slug it out in the ring. Who will be this year's champion?",
      "poster_path": "/tZDxttt0LfgAKwvLIWyOO3fr01c.jpg"
    },
    {
      "popularity": 0.6,
      "id": 295477,
      "video": false,
      "vote_count": 0,
      "vote_average": 0,
      "title": "Fight club camp kusse",
      "release_date": "2005-08-12",
      "original_language": "da",
      "original_title": "Fight club camp kusse",
      "genre_ids": [],
      "backdrop_path": null,
      "adult": false,
      "overview": "",
      "poster_path": "/4kQyWM9i2UwLcbScNeIn1YTm7HT.jpg"
    },
    {
      "popularity": 0.6,
      "vote_count": 0,
      "video": false,
      "poster_path": "/yrOE92bDvzClGDpsDu8JkUssuuA.jpg",
      "id": 488671,
      "adult": false,
      "backdrop_path": "/A34w8ugqo1i9lah6nOgQONocs0D.jpg",
      "original_language": "da",
      "original_title": "Comedy Fight Club Live",
      "genre_ids": [
        35
      ],
      "title": "Comedy Fight Club Live",
      "vote_average": 0,
      "overview": "",
      "release_date": "2017-04-03"
    },
    {
      "popularity": 0.6,
      "genre_ids": [
        99
      ],
      "video": false,
      "vote_count": 1,
      "original_language": "en",
      "adult": false,
      "title": "Brooklyn Girls Fight Club",
      "original_title": "Brooklyn Girls Fight Club",
      "backdrop_path": null,
      "id": 209599,
      "vote_average": 7,
      "overview": "From the birthplace of boxing legend Mike Tyson, young women brawl in secret fight clubs to win $1000 and invaluable street cred.",
      "poster_path": null
    },
    {
      "popularity": 0.6,
      "id": 468371,
      "video": false,
      "vote_count": 0,
      "vote_average": 0,
      "title": "Nixon Newell: First Female of Fight Club",
      "release_date": "2017-07-26",
      "original_language": "en",
      "original_title": "Nixon Newell: First Female of Fight Club",
      "genre_ids": [
        99
      ],
      "backdrop_path": null,
      "adult": false,
      "overview": "Since 2013, Nixon Newell has travelled the world as a professional wrestler. This is the story of her goodbye to independent wrestling.",
      "poster_path": null
    },
    {
      "popularity": 1.4,
      "id": 615408,
      "video": false,
      "vote_count": 0,
      "vote_average": 0,
      "title": "Fight Club But With Tennis And No Fight",
      "release_date": "2019-07-13",
      "original_language": "en",
      "original_title": "Fight Club But With Tennis And No Fight",
      "genre_ids": [
        16,
        35
      ],
      "backdrop_path": null,
      "adult": false,
      "overview": "Drama descends upon two tennis-obsessed women as the tension moves from off the court and into the café.",
      "poster_path": "/8pEQqVtSpgCtb7dzhR55EO1dC3l.jpg"
    },
    {
      "popularity": 0.6,
      "vote_count": 0,
      "video": false,
      "poster_path": null,
      "id": 653285,
      "adult": false,
      "backdrop_path": null,
      "original_language": "en",
      "original_title": "Fight Club Pro Project Mayhem VIII Night One",
      "genre_ids": [],
      "title": "Fight Club Pro Project Mayhem VIII Night One",
      "vote_average": 0,
      "overview": "The rivalry between Fight Club: PRO management and the Schadenfreude faction led by Tipton’s Chris Brookes ended in stunning fashion across both nights of the promotion’s eighth annual Project Mayhem weekender.  Night one events followed by a second night of action.",
      "release_date": "2019-09-27"
    },
    {
      "popularity": 0.6,
      "vote_count": 0,
      "video": false,
      "poster_path": null,
      "id": 653286,
      "adult": false,
      "backdrop_path": null,
      "original_language": "en",
      "original_title": "Fight Club Pro Project Mayhem VIII Night Two",
      "genre_ids": [],
      "title": "Fight Club Pro Project Mayhem VIII Night Two",
      "vote_average": 0,
      "overview": "The rules saw participants enter in staggered intervals, with the last person due to enter being Wolverhampton’s Trent Seven. However the WWE superstar never made it to the ring, ultimately being thrown off the entrance stage and through a table.  Fight Club: PRO wouldn’t be disadvantaged for long, with Jimmy Havoc making yet another surprise appearance at Project Mayhem, to aid the promotion.  Birmingham’s Dan Moloney would ultimately secure the pinfall for Fight Club: PRO, piledriving Kyle Fletcher through a table.",
      "release_date": "2019-09-28"
    }
  ]
}`

Полученное сообщение об ошибке:

'невозможно преобразовать массив в строку'

Примечание. Мой ключ API имеет строковое значение placeholdeR, так как ключ должен храниться полностью закрытым, в моей программе он имеет истинное значение, а не этот заполнитель

Ответы [ 2 ]

0 голосов
/ 19 марта 2020

Я решил эту проблему с помощью Это видео на Youtube , мой исправленный код выглядит следующим образом

Imports System.IO
Imports System.Net
Imports Newtonsoft.Json.Linq
Public Class TMDb_Connection
    Private API_Key As String = "My API key here"
    Private API_url As String = "https://api.themoviedb.org/3"
    Private API_Image_Base_url As String = "https://image.tmdb.org/t/p/w500/"
    Private API_Pagination As String = "1"

    Public Sub SearchAPI(ByVal API_Query As String, ByVal ObjectToken As String)
        Dim Response As HttpWebResponse
        Dim postData As String = "api_key=" & API_Key & "&query=" & WebUtility.UrlEncode(API_Query)
        Dim Request As HttpWebRequest = DirectCast(HttpWebRequest.Create(API_url & "/search/movie?" & postData), HttpWebRequest)
        Request.Method = "GET"

        Try
            Response = DirectCast(Request.GetResponse(), HttpWebResponse)
            Dim Stream As Stream = Response.GetResponseStream()
            Dim reader As New StreamReader(Stream, Encoding.GetEncoding("utf-8"))
            Dim responseFromServer As String = reader.ReadToEnd()
            reader.Close()
            Response.Close()
            Dim obj As JObject = JObject.Parse(responseFromServer)
            Dim objarray As JArray = JArray.Parse(obj.SelectToken("results").ToString)
            Dim temp As String = ""
            For Each results As JObject In objarray
                temp = temp & results.SelectToken("id").ToString() & ", "
            Next
            MsgBox(temp)
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

этот код создаст окно сообщения со всеми идентификаторами фильмы распечатаны по порядку. Кажется, синтаксический анализ JSON пытался проанализировать каждый идентификатор каждого mov ie, но не смог, потому что его не было в массиве, хотя я до сих пор не до конца понимаю его сам. Я надеюсь, что это поможет любому, кто сталкивается с этим и не стесняется задавать больше вопросов, хотя я не гарантированно знаю ответ! Большое спасибо всем, кто помог мне!

0 голосов
/ 17 марта 2020

Ваши результаты находятся в массиве - списке фильмов.

Попробуйте изменить тип для этого с As String на As JObject и затем работать с результатами оттуда.

Dim obj2 As String = JObject.Parse(obj.SelectToken("results"))

...