Generic Page Json

CSharp · Console

/Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
					
public class Program
    {
        public static void Main()
        {

            try
            {
                string json = @"
                {
                  ""LinkType1"": ""google"",
                  ""LinkUrl1"": ""https://plus.google.com/test"",
                  ""LinkShow1"": 1,
                  ""LinkType2"": ""facebook"",
                  ""LinkUrl2"": ""https://www.facebook.com/test"",
                  ""LinkShow2"": 0,
                  ""LinkType3"": ""linkedin"",
                  ""LinkUrl3"": ""http://www.linkedin.com/test"",
                  ""LinkShow3"": 1,
                  ""count"": 3,
                  ""errorCode"": 0,
                  ""errorMessage"": ""Success""
                }";

                LinksResult result = JsonConvert.DeserializeObject<LinksResult>(json);
                foreach (LinkData link in result.PageItems)
                {
                    Console.WriteLine(string.Format("{0}: {1} ({2})", link.LinkType, link.LinkUrl, (link.LinkShow ? "show" : "hide")));
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex.ToString());
            }
        }
    }

    public interface IPage<TItem>
    {
        int Count { get; set; }
        List<TItem> PageItems { get; set; }
    }

    public class PageConverter<TPage, TItem> : JsonConverter
            where TPage : IPage<TItem>, new()
            where TItem : new()
    {
        private readonly Regex _numberPostfixRegex = new Regex(@"\d+$");

        public override bool CanWrite
        {
            get { return false; }
        }

        public override bool CanConvert(Type objectType)
        {
            return (objectType == typeof(TPage));
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var obj = serializer.Deserialize<JObject>(reader);
            var page = new TPage();
            serializer.Populate(obj.CreateReader(), page); //Loads everything that isn't a part of the items. 
            page.PageItems = new List<TItem>();

            for (int i = 1; i <= page.Count; i++)
            {
                string index = i.ToString();

                //Find all properties that have a number at the end, then any of those that are the same number as the current index.
                //Put those in a new JObject.
                var jsonItem = new JObject();
                foreach (var prop in obj.Properties().Where(p => _numberPostfixRegex.Match(p.Name).Value == index))
                {
                    jsonItem[_numberPostfixRegex.Replace(prop.Name, "")] = prop.Value;
                }

                //Deserialize and add to the list.
                TItem item = jsonItem.ToObject<TItem>(serializer);
                page.PageItems.Add(item);
            }

            return page;
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }
    }

    [JsonConverter(typeof(PageConverter<LinksResult, LinkData>))]
    public class LinksResult : IPage<LinkData>
    {
        public int Count { get; set; }

        public List<LinkData> PageItems { get; set; }
    }

    public class LinkData
    {
        public string LinkType { get; set; }
        public string LinkUrl { get; set; }
        public bool LinkShow { get; set; }
    }
;