Convert Coveo Rest API JSON result into object using custom Deserialize

Convert Coveo Rest API JSON result into object using custom Deserialize

When we use the Coveo Rest API by passing parameters to get the results in JSON, it provides a lots of things in the results, and creating class and properties for all these result is a tedious work. And also in our case we don’t require all the result properties and creating multiple classes for the different value will make the thing complex. So we have decided to use Json to object converter, but problem arrives when we don’t know the properties returns in the result because result can return any type of sitecore page item. One solution we have use to create a Dynamic Json Converter. So how it is going to work? We got the result by making call to the coveo cloud and passing query and then we need to deserialize using the custom deserialize.

            var result = MakeCoveoRequest.MakeRequest(q);

var serializer = new JavaScriptSerializer();

serializer.RegisterConverters(new[] { new DynamicJsonConverter() });

dynamic obj = serializer.Deserialize(result, typeof(object));

we need to create as instance of the JavaScriptSerializer and then we need to registor the convertor with our custom dynamic Json convertor. Now the object of the JavaScriptSerializer will deserialize the result in dynamic object.

Our Custom DynamicJsonConverter will override default Deserialize function to convert the json into dictionary key value pair where key will be dynamic object property and value will be value or any dynamic object.

using System;

using System.Collections;

using System.Collections.Generic;

using System.Collections.ObjectModel;

using System.Dynamic;

using System.Linq;

using System.Text;

using System.Web.Script.Serialization;

 

namespace MyNameSpace

{

public class DynamicJsonConverter : JavaScriptConverter

{

public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)

{

if (dictionary == null)

throw new ArgumentNullException(“dictionary”);

 

return type == typeof(object) ? new DynamicJsonObject(dictionary) : null;

}

 

public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)

{

throw new NotImplementedException();

}

 

public override IEnumerable<Type> SupportedTypes

{

get { return new ReadOnlyCollection<Type>(new List<Type>(new[] { typeof(object) })); }

}

 

#region Nested type: DynamicJsonObject

 

private sealed class DynamicJsonObject : DynamicObject

{

private readonly IDictionary<string, object> _dictionary;

 

public DynamicJsonObject(IDictionary<string, object> dictionary)

{

if (dictionary == null)

throw new ArgumentNullException(“dictionary”);

_dictionary = dictionary;

}

 

public override string ToString()

{

var sb = new StringBuilder(“{“);

ToString(sb);

return sb.ToString();

}

 

private void ToString(StringBuilder sb)

{

var firstInDictionary = true;

foreach (var pair in _dictionary)

{

if (!firstInDictionary)

sb.Append(“,”);

firstInDictionary = false;

var value = pair.Value;

var name = pair.Key;

if (value is string)

{

sb.AppendFormat(“{0}:\”{1}\””, name, value);

}

else if (value is IDictionary<string, object>)

{

new DynamicJsonObject((IDictionary<string, object>)value).ToString(sb);

}

else if (value is ArrayList)

{

sb.Append(name + “:[“);

var firstInArray = true;

foreach (var arrayValue in (ArrayList)value)

{

if (!firstInArray)

sb.Append(“,”);

firstInArray = false;

if (arrayValue is IDictionary<string, object>)

new DynamicJsonObject((IDictionary<string, object>)arrayValue).ToString(sb);

else if (arrayValue is string)

sb.AppendFormat(“\”{0}\””, arrayValue);

else

sb.AppendFormat(“{0}”, arrayValue);

 

}

sb.Append(“]”);

}

else

{

sb.AppendFormat(“{0}:{1}”, name, value);

}

}

sb.Append(“}”);

}

 

public override bool TryGetMember(GetMemberBinder binder, out object result)

{

if (!_dictionary.TryGetValue(binder.Name, out result))

{

// return null to avoid exception.  caller can check for null this way…

result = null;

return true;

}

 

result = WrapResultObject(result);

return true;

}

 

public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result)

{

if (indexes.Length == 1 && indexes[0] != null)

{

if (!_dictionary.TryGetValue(indexes[0].ToString(), out result))

{

// return null to avoid exception.  caller can check for null this way…

result = null;

return true;

}

 

result = WrapResultObject(result);

return true;

}

 

return base.TryGetIndex(binder, indexes, out result);

}

 

private static object WrapResultObject(object result)

{

var dictionary = result as IDictionary<string, object>;

if (dictionary != null)

return new DynamicJsonObject(dictionary);

 

var arrayList = result as ArrayList;

if (arrayList != null && arrayList.Count > 0)

{

return arrayList[0] is IDictionary<string, object>

? new List<object>(arrayList.Cast<IDictionary<string, object>>().Select(x => new DynamicJsonObject(x)))

: new List<object>(arrayList.Cast<object>());

}

 

return result;

}

}

}

#endregion

}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s