U
U
Urope2020-12-25 11:28:16
C++ / C#
Urope, 2020-12-25 11:28:16

How to output only certain elements from json?

I make a request to api:

var client = new RestClient("https://api.kinopoisk.cloud/");
var request = new RestRequest($"movies/search/{movieTitle}/token/{TOKEN}", Method.GET);
var response = client.Execute(request).Content;


the problem is that the api returns a bunch of unnecessary data. For example, I'm looking for information on the movie "fool", and the information on the films is returned: "fool", "there are no fools", and so on.

5fe5a16b32113996748408.png
How can I get information from here only about the movie I need? I noticed that the right one is always the very first, so you need to somehow take the information from the first element of the array?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
B
Boris the Animal, 2020-12-26
@Urope

You take your request. You open the Postman program . You send a request. Copy the resulting JSON to the clipboard. You go to some site like https://json2csharp.com/ and paste the JSON there. You copy the received classes, correctly you name. Class generation options:
5fe665235f0a1045486034.png
By the way, for the search query (text), you can try using Uri.EscapeUriString
Connecting the fast System.Text.Json serializer from .NET Core
RestSharpExample.csproj

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp3.1</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="RestSharp" Version="106.11.7" />
    <PackageReference Include="RestSharp.Serializers.SystemTextJson" Version="106.11.7" />
  </ItemGroup>

</Project>

API/Kinopoisk/ KinopoiskService.cs
using System.Threading.Tasks;
using System.Web;
using RestSharp;
using RestSharp.Serializers.SystemTextJson;
using RestSharpExample.Api.Kinopoisk.Model;

namespace RestSharpExample.Api.Kinopoisk
{
    public class KinopoiskService
    {
        private const string API = "https://api.kinopoisk.cloud/";
        private const string TOKEN = "7777";

        private readonly RestClient _client;

        public KinopoiskService()
        {
            _client = new RestClient(API);
            _client.UseSystemTextJson();
        }

        public async Task<SearchResult> SearchAsync(string movieTitle)
        {
            var request = new RestRequest($"movies/search/{HttpUtility.UrlEncode(movieTitle)}/token/{TOKEN}", Method.GET);
            var response = await _client.ExecuteAsync<SearchResult>(request);
            return response.Data;
        }
    }
}

Program.cs
using System;
using System.Linq;
using System.Threading.Tasks;
using RestSharpExample.Api.Kinopoisk;
using RestSharpExample.Api.Kinopoisk.Model;

namespace RestSharpExample
{
    class Program
    {
        private KinopoiskService _kinopoisk;

        #region Entry point

        static async Task Main(string[] args)
        {
            var program = new Program();
            await program.Run(args);
        }

        #endregion

        private async Task Run(string[] args)
        {
            _kinopoisk = new KinopoiskService();

            try
            {
                string searchRequest = "Дурак";
                SearchResult result = await _kinopoisk.SearchAsync(searchRequest);
                Console.WriteLine($"Результаты поиска по запросу \"{searchRequest}\":");
                if (result.Results.Any())
                {
                    Display(result.Results.First());
                }
                else
                {
                    Console.WriteLine("Ничего не найдено.");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }

        private void Display(SearchMovieInfo info)
        {
            Console.WriteLine($"ИД: {info.Id}, Название: {info.Title}, Год: {info.Year}");
        }
    }
}

API/Kinopoisk/Model/ SearchResult.cs
using System.Collections.Generic;
using System.Text.Json.Serialization;

namespace RestSharpExample.Api.Kinopoisk.Model
{
    public class SearchResult
    {
        [JsonPropertyName("results")]
        public List<SearchMovieInfo> Results { get; set; }

        [JsonPropertyName("pagination")]
        public Pagination Pagination { get; set; }
    }
}

API/Kinopoisk/Model/ SearchMovieInfo.cs
using System.Text.Json.Serialization;

namespace RestSharpExample.Api.Kinopoisk.Model
{
    public class SearchMovieInfo
    {
        [JsonPropertyName("id")]
        public string Id { get; set; }

        [JsonPropertyName("id_kinopoisk")]
        public int IdKinopoisk { get; set; }

        [JsonPropertyName("title")]
        public string Title { get; set; }

        [JsonPropertyName("description")]
        public string Description { get; set; }

        [JsonPropertyName("year")]
        public int Year { get; set; }

        [JsonPropertyName("poster")]
        public string Poster { get; set; }

        [JsonPropertyName("rating_kinopoisk")]
        public double? RatingKinopoisk { get; set; }

        [JsonPropertyName("rating_imdb")]
        public double? RatingImdb { get; set; }
    }

API/Kinopoisk/Model/ Pagination.cs
using System.Text.Json.Serialization;

namespace RestSharpExample.Api.Kinopoisk.Model
{
    public class Pagination
    {
        [JsonPropertyName("current_page")]
        public string CurrentPage { get; set; }

        [JsonPropertyName("end_page")]
        public string EndPage { get; set; }

        [JsonPropertyName("total_pages")]
        public int TotalPages { get; set; }
    }
}

V
Vasily Bannikov, 2020-12-25
@vabka

There is a Execute<T> method into which you can throw the desired type
. Throw something like FilmInfo[] there and take from the result [0]

F
freeExec, 2020-12-25
@freeExec

https://www.newtonsoft.com/json

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question