Saturday, August 6, 2016

Json Serializer | Serializing Interface and Generic List

Json Serialization though can be very easy but there are situations when it is not very straight forward, specially when it is one of the following cases:
1. An interface object
2. List of objects
3. IList of objects
4. List of interface
5. IList of interface

So, you can utilize the generic code below to solve the problem:

You need to install Newtonsoft.JSON to use this code:


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

namespace Utilities.Core
{
    public static class JsonSerializer<T> where T : class
    {
        public static string ToJson(T objectToSerialize)
        {
            if (null == objectToSerialize)
                return null;
            return JsonConvert.SerializeObject(objectToSerialize);
        }

        public static T ToObject(string json)
        {
            if (string.IsNullOrWhiteSpace(json))
                return null;
            return JsonConvert.DeserializeObject<T>(json);
        }

        public static List<T> ToObjectList(string json)
        {
            if (string.IsNullOrWhiteSpace(json))
                return null;
            return JsonConvert.DeserializeObject<List<T>>(json);
        }
    }

    public static class JsonSerializer<TImplementation, TInterface> where TImplementation : class, TInterface
    {
        public static string ToJson(TInterface objectToSerialize)
        {
            if (null == objectToSerialize)
                return null;
            return JsonConvert.SerializeObject(objectToSerialize);
        }

        public static TInterface ToObject(string json)
        {
            return JsonSerializer<TImplementation>.ToObject(json);
        }

        public static IList<TInterface> ToObjectList(string json)
        {
            if (string.IsNullOrWhiteSpace(json))
                return null;
            var results = JsonConvert.DeserializeObject<List<TImplementation>>(json);
            IList<TInterface> objectList = results.Select(item => (TInterface) item).ToList();
            return objectList;
        }
    }
}

No comments:

Post a Comment