allow use of json.net serialization via an extra optional arg. Close #78
diff --git a/template/cordovalib/JSON/JsonHelper.cs b/template/cordovalib/JSON/JsonHelper.cs
index 77c7233..1e8953c 100644
--- a/template/cordovalib/JSON/JsonHelper.cs
+++ b/template/cordovalib/JSON/JsonHelper.cs
@@ -17,6 +17,7 @@
using System.IO;
using System.Text;
using System.Diagnostics;
+using Newtonsoft.Json;
namespace WPCordovaClassLib.Cordova.JSON
{
@@ -30,31 +31,38 @@
/// </summary>
/// <param name="obj">object to serialize</param>
/// <returns>JSON representation of the object. Returns 'null' string for null passed as argument</returns>
- public static string Serialize(object obj)
+ public static string Serialize(object obj, bool bUseJsonDotNet = false)
{
- if (obj == null)
+ if (bUseJsonDotNet)
+ {
+ return JsonConvert.SerializeObject(obj);
+ }
+ else if (obj == null)
{
return "null";
}
-
- DataContractJsonSerializer ser = new DataContractJsonSerializer(obj.GetType());
-
- MemoryStream ms = new MemoryStream();
- ser.WriteObject(ms, obj);
-
- ms.Position = 0;
-
- string json = String.Empty;
-
- using (StreamReader sr = new StreamReader(ms))
+ else
{
- json = sr.ReadToEnd();
+
+ DataContractJsonSerializer ser = new DataContractJsonSerializer(obj.GetType());
+
+ MemoryStream ms = new MemoryStream();
+ ser.WriteObject(ms, obj);
+
+ ms.Position = 0;
+
+ string json = String.Empty;
+
+ using (StreamReader sr = new StreamReader(ms))
+ {
+ json = sr.ReadToEnd();
+ }
+
+ ms.Close();
+
+ return json;
}
- ms.Close();
-
- return json;
-
}
/// <summary>
@@ -63,24 +71,32 @@
/// <typeparam name="T">type of the object</typeparam>
/// <param name="json">json string representation of the object</param>
/// <returns>Deserialized object instance</returns>
- public static T Deserialize<T>(string json)
+ public static T Deserialize<T>(string json, bool bUseJsonDotNet = false)
{
- DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(T));
- object result = null;
- try
- {
- using (MemoryStream mem = new MemoryStream(Encoding.UTF8.GetBytes(json)))
- {
- result = deserializer.ReadObject(mem);
- }
- }
- catch (Exception ex)
- {
- Debug.WriteLine(ex.Message);
- Debug.WriteLine("Failed to deserialize " + typeof(T) + " with JSON value :: " + json);
- }
- return (T)result;
+ if (bUseJsonDotNet)
+ {
+ return JsonConvert.DeserializeObject<T>(json);
+ }
+ else
+ {
+ DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(T));
+ object result = null;
+ try
+ {
+ using (MemoryStream mem = new MemoryStream(Encoding.UTF8.GetBytes(json)))
+ {
+ result = deserializer.ReadObject(mem);
+ }
+ }
+ catch (Exception ex)
+ {
+ Debug.WriteLine(ex.Message);
+ Debug.WriteLine("Failed to deserialize " + typeof(T) + " with JSON value :: " + json);
+ }
+
+ return (T)result;
+ }
}
}