2

I want to call an api that the answer to this api is a list of outputs in the form of Json. How can I set a list of models? my models

public class JsonModel
    {
        public bool IsAuthorize{ get; set; }
        public string Service { get; set; }
        public int Age{ get; set; }
    }
  • 1
    You need a JSON de/serializer. [Newtonsoft](https://www.newtonsoft.com/json) is the most popular. – Ergis Apr 25 '22 at 08:01
  • 1
    Does this answer your question? [Deserialize JSON with C#](https://stackoverflow.com/questions/7895105/deserialize-json-with-c-sharp) – Ergis Apr 25 '22 at 08:02

1 Answers1

2

Using Newtonsoft, which is the most popular JSON framework for .NET:

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RestSharp;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

static void Main(string[] args)
    {
        var client = new RestClient("your api url");
        client.Timeout = -1;
        var request = new RestRequest("Method type");
        var response = client.Execute(request);
        var res = JsonConvert.DeserializeObject<JObject>(response.Content);

        foreach (var token in res.Children())
        {
            if (token is JProperty)
            {
                var prop = JsonConvert.DeserializeObject<JsonModel>(token.First().ToString());
                Console.WriteLine($"IsAuthorize : {prop.IsAuthorize} , Service : {prop.Service} , Age : {prop.Age} ");
            }
        }
        Console.ReadKey();
    }

    public class JsonModel
    {
        public bool IsAuthorize { get; set; }
        public string Service { get; set; }
        public int Age { get; set; }
    }
mehdi farhadi
  • 1,415
  • 1
  • 10
  • 16
  • 6
    What is better than using the Newtonsoft package? Your answer looks like you _are using_ the Newtonsoft package. – ProgrammingLlama Apr 25 '22 at 08:02
  • 1
    In newer versions of dotnet, I'D actually recommend System.Text.Json over Newtonsoft. It usually performs better. Newtonsoft focussed on giving a wide variety of Features, not performance. So, if you need/want a feature that System.Text.Json doesn't have and you don't care so much on runtime performance, only then would I consider Newtonsoft (in recent .NET / .NET Core versions). – Fildor Apr 25 '22 at 08:08
  • @Fildor tho, utilizing source generators both perform even better and almost the same, while newtonsoft is still more feature rich – Patrick Beynio Apr 25 '22 at 10:56