Home > database >  how to cast json to list of models in c#?
how to cast json to list of models in c#?

Time:04-25

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; }
    }

CodePudding user response:

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; }
    }
  • Related