如何将JSON结果导入List

时间:2015-12-21 16:57:47

标签: c# interface json.net

我在这里有自己的代码并且已经获得了JSON结果,然后我不知道将JSON结果移动到下面的接口(IEntities函数)列表中。

class GetCategory : IEntities
{
    private JsonHandle _jsonhandle;
    private string _ocategory;

    public async void TaskCategory()
    {
        _jsonhandle = new JsonHandle();
        _jsonhandle.StrAPI = "http://api.nytimes.com/svc/books/v3/lists/names.json?api-key=7bb034b7693d6f9753b2f68e00b98c78%3A16%3A73599437";
        var client = new HttpClient();
        Task<string> datatask = client.GetStringAsync(_jsonhandle.StrAPI);
        try
        {
            var JsonRead = await datatask;
            JObject oCategory = JObject.Parse(JsonRead);
            List<JToken> results = oCategory["results"].Children().ToList();

            //serialize JSON results into .NET objects
            List<object> dtCategory = new List<object>();
            foreach (JToken result in results)
            {
                object _dtcategory = JsonConvert.DeserializeObject<object>(result.ToString());
                dtCategory.Add(_dtcategory);
                var listname = result["list_name"];
            }
        }
        catch (Exception error)
        {
            Console.WriteLine("AW!" + error.StackTrace);
        }

    public List<object> BookCategory()
    {

    }
}

IEntities接口的最后一个函数中,我需要将JSON结果放在接口List<object>中。

1 个答案:

答案 0 :(得分:4)

使用 JSON 时,首先要做的是创建模型对象。为此,您应该手动分析 JSON 输出,或者您可以通过转到以下链接自动生成模型并粘贴您要使用的JSON或服务链接;

json2csharp.com

我刚刚使用了您的API链接,生成的输出是;

public class Result
{
    public string list_name { get; set; }
    public string display_name { get; set; }
    public string list_name_encoded { get; set; }
    public string oldest_published_date { get; set; }
    public string newest_published_date { get; set; }
    public string updated { get; set; }
}

public class RootObject
{
    public string status { get; set; }
    public string copyright { get; set; }
    public int num_results { get; set; }
    public List<Result> results { get; set; }
}

这将是我们的模型。

其次,据我所知,您想要做的只是获取结果列表,因此,当您反序列化 JSON 输出时,您将使用 Model.Result 并将其移至列表

然后,要获得响应,可以使用返回async Task<string>的私有方法,并且在BookCategory()方法上,您可以获取结果并反序列化 JSON 并根据 JSON对象模型;

初始化列表
public List<Model.Result> BookCategory()
{
    List<Model.Result> list = new List<Model.Result>();

    var model = JsonConvert.DeserializeObject<Model.RootObject>(TaskCategory().Result);

    list = model.results;

    return list;
}

反序列化JSON 就像下面一样;

var model = JsonConvert.DeserializeObject<Model.RootObject>(TaskCategory().Result);

Model.cs

using System.Collections.Generic;

namespace SO1
{
    public class Model
    {
        public class Result
        {
            public string list_name { get; set; }
            public string display_name { get; set; }
            public string list_name_encoded { get; set; }
            public string oldest_published_date { get; set; }
            public string newest_published_date { get; set; }
            public string updated { get; set; }
        }

        public class RootObject
        {
            public string status { get; set; }
            public string copyright { get; set; }
            public int num_results { get; set; }
            public List<Result> results { get; set; }
        }
    }
}

GetCategory.cs

using Newtonsoft.Json;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Net.Http;
using System;

namespace SO1
{
    public class GetCategory : IEntities
    {
        private String BaseUri;

        public GetCategory(string BaseUri)
        {
            this.BaseUri = BaseUri;
        }

        private async Task<string> TaskCategory()
        {
            var httpClient = new HttpClient();

            var parameters = new Dictionary<string, string>();
            parameters["text"] = "text";

            var response = await httpClient.GetStringAsync(BaseUri);

            return response;        
        }

        public List<Model.Result> BookCategory()
        {
            List<Model.Result> list = new List<Model.Result>();

            var model = JsonConvert.DeserializeObject<Model.RootObject>(TaskCategory().Result);

            list = model.results;

            return list;
        }

    }
}

IEntities

using System.Collections.Generic;

namespace SO1
{
    public interface IEntities
    {
        List<Model.Result> BookCategory();
    }
}

的Program.cs

using System;
using System.Collections.Generic;

namespace SO1
{
    class Program
    {
        static void Main(string[] args)
        {
            string BaseUri = "http://api.nytimes.com/svc/books/v3/lists/names.json?api-key=7bb034b7693d6f9753b2f68e00b98c78%3A16%3A73599437";

            IEntities entity = new GetCategory(BaseUri);

            List<Model.Result> listBookCategory = new List<Model.Result>();

            listBookCategory = entity.BookCategory();

            foreach (Model.Result r in listBookCategory)
            {
                Console.WriteLine();
                Console.WriteLine("...List Name             : " + r.list_name);
                Console.WriteLine("...Display Name          : " + r.display_name);
                Console.WriteLine("...List Name Encoded     : " + r.list_name_encoded);
                Console.WriteLine("...Oldest Published Date : " + r.oldest_published_date);
                Console.WriteLine("...Oldest Published Date : " + r.newest_published_date);
                Console.WriteLine("...Updated               : " + r.updated);
                Console.WriteLine();
            }
        }
    }
}

输出(仅打印前三个结果)

...List Name             : Combined Print and E-Book Fiction
...Display Name          : Combined Print & E-Book Fiction
...List Name Encoded     : combined-print-and-e-book-fiction
...Oldest Published Date : 2011-02-13
...Oldest Published Date : 2015-12-27
...Updated               : WEEKLY


...List Name             : Combined Print and E-Book Nonfiction
...Display Name          : Combined Print & E-Book Nonfiction
...List Name Encoded     : combined-print-and-e-book-nonfiction
...Oldest Published Date : 2011-02-13
...Oldest Published Date : 2015-12-27
...Updated               : WEEKLY


...List Name             : Hardcover Fiction
...Display Name          : Hardcover Fiction
...List Name Encoded     : hardcover-fiction
...Oldest Published Date : 2008-06-08
...Oldest Published Date : 2015-12-27
...Updated               : WEEKLY