c#将多个Json反序列化为相同的列表

时间:2015-04-04 17:57:32

标签: c# json list serialization

我有一个返回此Json structure的Api链接。在代码中,我请求此Api链接,然后将其反序列化为列表。这没有问题。但如果Api返回超过50“计数”,则会创建另一页。我如何绕过所有页面并将所有内容添加到现有列表中?

在我链接的情况下,将有38页。所有这些都需要添加到列表中。

呼叫

    // spidyApiUrl = http://www.gw2spidy.com/api/v0.9/json/item-search/iron/1
var spidyApi_idByName_result = api_Handler.objFromApi_idToName(spidyApiUrl);

返回

的功能
public RootObject objFromApi_idToName(string url)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            WebResponse response = request.GetResponse();
            using (Stream responseStream = response.GetResponseStream())
            {
                StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
                var jsonReader = new JsonTextReader(reader);
                var serializer = new JsonSerializer();
                //return serializer.Deserialize<RootObject>(jsonReader);
                RootObject rootObject = serializer.Deserialize<RootObject>(jsonReader);

                if (rootObject.count > 0) { return rootObject; }
                else { return null; }

            }

        }

当然,我也有get; set;类。

如何遍历所有页面(如果存在多个页面,则不必),并将这些页面添加到同一个对象列表中。

2 个答案:

答案 0 :(得分:1)

您需要继续下载数据,直至page == last_page 当您获得每个数据页面时,然后使用AddRange将新的results集添加到原始rootObject的results属性

我还更改了从

传递到函数的url
http://www.gw2spidy.com/api/v0.9/json/item-search/iron/1

http://www.gw2spidy.com/api/v0.9/json/item-search/iron

这允许我将页码添加到网址以获取所有页面

http://www.gw2spidy.com/api/v0.9/json/item-search/iron/1
http://www.gw2spidy.com/api/v0.9/json/item-search/iron/2
.....
http://www.gw2spidy.com/api/v0.9/json/item-search/iron/38

代码:

public class Result
{
    public int data_id { get; set; }
    public string name { get; set; }
    public int rarity { get; set; }
    public int restriction_level { get; set; }
    public string img { get; set; }
    public int type_id { get; set; }
    public int sub_type_id { get; set; }
    public string price_last_changed { get; set; }
    public int max_offer_unit_price { get; set; }
    public int min_sale_unit_price { get; set; }
    public int offer_availability { get; set; }
    public int sale_availability { get; set; }
    public int sale_price_change_last_hour { get; set; }
    public int offer_price_change_last_hour { get; set; }
}

public class RootObject
{
    public int count { get; set; }
    public int page { get; set; }
    public int last_page { get; set; }
    public int total { get; set; }
    public List<Result> results { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        objFromApi_idToName("http://www.gw2spidy.com/api/v0.9/json/item-search/iron");
    }

    public static RootObject objFromApi_idToName(string url)
    {
        RootObject rootObject = null;
        RootObject tempRootObject = null;
        int page = 1;
        do
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url + "/" + page);

            WebResponse response = request.GetResponse();
            using (Stream responseStream = response.GetResponseStream())
            {
                StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
                var jsonReader = new JsonTextReader(reader);
                var serializer = new JsonSerializer();
                //return serializer.Deserialize<RootObject>(jsonReader);
                tempRootObject = serializer.Deserialize<RootObject>(jsonReader);

                if (rootObject == null)
                {
                    rootObject = tempRootObject;
                }
                else
                {
                    rootObject.results.AddRange(tempRootObject.results);
                    rootObject.count += tempRootObject.count;
                }
            }
            page++;
        } while (tempRootObject != null && tempRootObject.last_page != tempRootObject.page);
        return rootObject;
    }
}

答案 1 :(得分:0)

您使用的是Web API吗?如果是这样,你会尝试这样的事吗?

public RootObject objFromApi_idToName(string url)
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("<your uri here>");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            HttpResponseMessage response = await client.GetAsync("<uri extention here>");
            if (response.IsSuccessStatusCode)
            {
                string jsonStr = await response.Content.ReadAsStringAsync();
                var deserializedResponse = JsonConvert.DeserializeObject<List<your model class here>>(jsonStr);
                return deserializedResponse;
        }
    }