unity C#: найти что-то в файле json из Интернета - PullRequest
0 голосов
/ 11 апреля 2020

Я просто хочу найти определенное свойство в довольно длинном JSON файле, который я получил через этот API . Просто хотите получить mov ie URL

{
  "data" :{
      "movies": [
           {
           "url" : [ENTER URL HERE]
           }
       ]  
    }
}

, просто хотите получить этот URL и программно поместить его в переменную для открытия в браузере и, возможно, для отображения в приложении

Script который получает код и делает json читабельным для людей:

using System.Collections;
using System.Collections.Generic;
using System.IO;
using Newtonsoft.Json;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.Serialization;
using UnityEngine.XR.WSA.Sharing;
using System.Runtime.Serialization.Formatters.Binary; 
using System.IO;


public class GETFromYTS : MonoBehaviour
{
    [FormerlySerializedAs("URL")] public string url;

    void Start()
    {
        // A correct website page.
        StartCoroutine(GetRequest(url));
       //Application.OpenURL(url);

    }



    IEnumerator GetRequest(string uri)
    {
        using (UnityWebRequest webRequest = UnityWebRequest.Get(uri))
        {
            // Request and wait for the desired page.
            yield return webRequest.SendWebRequest();

            string[] pages = uri.Split('/');
            int page = pages.Length - 1;

            if (webRequest.isNetworkError)
            {
                Debug.Log(pages[page] + ": Error: " + webRequest.error);
            }
            else
            {

                string json = JsonConvert.DeserializeObject(webRequest.downloadHandler.text).ToString();
                Debug.Log(json);


            }    
        }
    }
}

, используя Jetbrains Rider в качестве IDE

полный json для дополнительной информации:

{
    "status": "ok",
    "status_message": "Query was successful",
    "data": {
        "movie_count": 1,
        "limit": 1,
        "page_number": 1,
        "movies": [
            {
                "id": 15813,
                "url": "https:\/\/yts.mx\/movie\/sonic-the-hedgehog-2020",
                "imdb_code": "tt3794354",
                "title": "Sonic the Hedgehog",
                "title_english": "Sonic the Hedgehog",
                "title_long": "Sonic the Hedgehog (2020)",
                "slug": "sonic- the-hedgehog-2020",
                "year": 2020,   
                "rating": 6.6,
                "runtime": 99,
                "genres": [
                    "Action",
                    "Adventure",
                    "Comedy",
                    "Family",
                    "Sci-Fi"
                ],
                "summary": "Based on the global blockbuster videogame franchise from Sega, SONIC THE HEDGEHOG tells the story of the world's speediest hedgehog as he embraces his new home on Earth. In this live-action adventure comedy, Sonic and his new best friend Tom (James Marsden) team up to defend the planet from the evil genius Dr. Robotnik (Jim Carrey) and his plans for world domination. The family-friendly film also stars Tika Sumpter and Ben Schwartz as the voice of Sonic.",
                "description_full": "Based on the global blockbuster videogame franchise from Sega, SONIC THE HEDGEHOG tells the story of the world's speediest hedgehog as he embraces his new home on Earth. In this live-action adventure comedy, Sonic and his new best friend Tom (James Marsden) team up to defend the planet from the evil genius Dr. Robotnik (Jim Carrey) and his plans for world domination. The family-friendly film also stars Tika Sumpter and Ben Schwartz as the voice of Sonic.",
                "synopsis": "Based on the global blockbuster videogame franchise from Sega, SONIC THE HEDGEHOG tells the story of the world's speediest hedgehog as he embraces his new home on Earth. In this live-action adventure comedy, Sonic and his new best friend Tom (James Marsden) team up to defend the planet from the evil genius Dr. Robotnik (Jim Carrey) and his plans for world domination. The family-friendly film also stars Tika Sumpter and Ben Schwartz as the voice of Sonic.",
                "yt_trailer_code": "szby7ZHLnkA",
                "language": "English",
                "mpa_rating": "PG",
                "background_image": "https:\/\/yts.mx\/assets\/images\/movies\/sonic_the_hedgehog_2020\/background.jpg",
                "background_image_original": "https:\/\/yts.mx\/assets\/images\/movies\/sonic_the_hedgehog_2020\/background.jpg",
                "small_cover_image": "https:\/\/yts.mx\/assets\/images\/movies\/sonic_the_hedgehog_2020\/small-cover.jpg",
                "medium_cover_image": "https:\/\/yts.mx\/assets\/images\/movies\/sonic_the_hedgehog_2020\/medium-cover.jpg",
                "large_cover_image": "https:\/\/yts.mx\/assets\/images\/movies\/sonic_the_hedgehog_2020\/large-cover.jpg",
                "state": "ok",
                "torrents": [
                    {
                        "url": "https:\/\/yts.mx\/torrent\/download\/77EFB6CF3336FCB8FC3FC67A222F548FF88BF00C",
                        "hash": "77EFB6CF3336FCB8FC3FC67A222F548FF88BF00C",
                        "quality": "720p",
                        "type": "web",
                        "seeds": 4441,
                        "peers": 736,
                        "size": "911.23 MB",
                        "size_bytes": 955493908,
                        "date_uploaded": "2020-03-08 19:31:51",
                        "date_uploaded_unix": 1583692311
                    },
                    {
                        "url": "https:\/\/yts.mx\/torrent\/download\/F3ACFD3979CC1A30CC7F312673CED688CE78CE77",
                        "hash": "F3ACFD3979CC1A30CC7F312673CED688CE78CE77",
                        "quality": "1080p",
                        "type": "web",
                        "seeds": 6737,
                        "peers": 1071,
                        "size": "1.65 GB",
                        "size_bytes": 1771674010,
                        "date_uploaded": "2020-03-08 21:15:14",
                        "date_uploaded_unix": 1583698514
                    }
                ],
                "date_uploaded": "2020-03-08 19:31:51",
                "date_uploaded_unix": 1583692311
            }
        ]
    },
    "@meta": {
        "server_time": 1586605584,
        "server_timezone": "CET",
        "api_version": 2,
        "execution_time": "0 ms"
    }
}

1 Ответ

0 голосов
/ 11 апреля 2020

Почему бы не использовать встроенный в Unity JsonUtility stati c класс? Просто объявите форму ваших данных с классом и конвертируйте JSON с ним.

[Serializable]
public class Movie 
{
   public string url;
   public string title;
   public string title_english;

   // Include every needed field
}

[Serializable]
public class Data
{
    public Movie[] movies;
}

[Serializable]
public class Response
{
    public Data data;
}

// ... everywhere you need 

Response res = JsonUtility.FromJson<Response>(json);

for (int i = 0; i < res.data.movies.Length; i++)
{
   Debug.Log(res.data.movies[i].url);
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...