PageRenderTime 43ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/packages/Facebook.6.0.16/serializers/JsonNetSerializer.cs

https://bitbucket.org/lduparc/berider
C# | 211 lines | 114 code | 18 blank | 79 comment | 12 complexity | 53eb6e852c49e78db1e61f4750d06641 MD5 | raw file
  1. //-----------------------------------------------------------------------
  2. // <copyright file="JsonNetSErializer.cs" company="The Outercurve Foundation">
  3. // Copyright (c) 2011, The Outercurve Foundation.
  4. //
  5. // Licensed under the Apache License, Version 2.0 (the "License");
  6. // you may not use this file except in compliance with the License.
  7. // You may obtain a copy of the License at
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS,
  12. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. // See the License for the specific language governing permissions and
  14. // limitations under the License.
  15. // </copyright>
  16. // <author>Nathan Totten (ntotten.com), Jim Zimmerman (jimzimmerman.com) and Prabir Shrestha (prabir.me)</author>
  17. // <website>https://github.com/facebook-csharp-sdk/facbook-csharp-sdk</website>
  18. //-----------------------------------------------------------------------
  19. namespace Facebook.Serializers
  20. {
  21. using System;
  22. using System.Collections.Generic;
  23. using System.Linq;
  24. using Newtonsoft.Json;
  25. using Newtonsoft.Json.Converters;
  26. using Newtonsoft.Json.Linq;
  27. /// <remarks>
  28. /// Install-Package Newtonsoft.Json
  29. /// It is recommended to set the the default json serializers during application startup.
  30. /// var jsonNetSerializer = new JsonNetSerializer();
  31. /// FacebookClient.SetDefaultJsonSerializers(jsonNetSerializer.SerializeObject, jsonNetSerializer.DeserializeObject);
  32. /// </remarks>
  33. public class JsonNetSerializer
  34. {
  35. private JsonSerializerSettings _serializerSettings;
  36. public JsonNetSerializer()
  37. {
  38. // Standard settings
  39. var isoDate = new IsoDateTimeConverter();
  40. isoDate.DateTimeFormat = "yyyy-MM-ddTHH:mm:sszzz";
  41. var settings = new JsonSerializerSettings();
  42. settings.Converters = settings.Converters ?? new List<JsonConverter>();
  43. settings.Converters.Add(isoDate);
  44. settings.MissingMemberHandling = MissingMemberHandling.Ignore;
  45. settings.NullValueHandling = NullValueHandling.Include;
  46. settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
  47. settings.TypeNameHandling = TypeNameHandling.None;
  48. settings.ConstructorHandling = ConstructorHandling.Default;
  49. _serializerSettings = settings;
  50. }
  51. /// <summary>
  52. /// Serializes the object to json string.
  53. /// </summary>
  54. /// <param name="obj">
  55. /// The value.
  56. /// </param>
  57. /// <returns>
  58. /// The json string.
  59. /// </returns>
  60. public string SerializeObject(object obj)
  61. {
  62. return JsonConvert.SerializeObject(obj, Formatting.None, this._serializerSettings);
  63. }
  64. /// <summary>
  65. /// Deserializes the json string.
  66. /// </summary>
  67. /// <param name="json">
  68. /// The json string.
  69. /// </param>
  70. /// <param name="type">
  71. /// The type of object.
  72. /// </param>
  73. /// <returns>
  74. /// The object.
  75. /// </returns>
  76. /// <exception cref="System.Runtime.Serialization.SerializationException">
  77. /// Occurs when deserialization fails.
  78. /// </exception>
  79. public object DeserializeObject(string json, Type type)
  80. {
  81. if (string.IsNullOrEmpty(json))
  82. {
  83. return null;
  84. }
  85. else
  86. {
  87. object obj;
  88. try
  89. {
  90. obj = JsonConvert.DeserializeObject(json, type, _serializerSettings);
  91. }
  92. catch (JsonSerializationException ex)
  93. {
  94. throw new System.Runtime.Serialization.SerializationException(ex.Message, ex);
  95. }
  96. // If the object is a JToken we want to
  97. // convert it to dynamic, it if is any
  98. // other type we just return it.
  99. var jToken = obj as JToken;
  100. if (jToken != null)
  101. {
  102. return ConvertJTokenToDictionary(jToken);
  103. }
  104. else
  105. {
  106. return obj;
  107. }
  108. }
  109. }
  110. /// <summary>
  111. /// Deserializes the object.
  112. /// </summary>
  113. /// <typeparam name="T">The type of the object.</typeparam>
  114. /// <param name="json">The json.</param>
  115. /// <returns></returns>
  116. public T DeserializeObject<T>(string json)
  117. {
  118. return (T)DeserializeObject(json, typeof(T));
  119. }
  120. /// <summary>
  121. /// Deserialize the json string to object.
  122. /// </summary>
  123. /// <param name="json">
  124. /// The json string.
  125. /// </param>
  126. /// <returns>
  127. /// The object.
  128. /// </returns>
  129. public object DeserializeObject(string json)
  130. {
  131. if (string.IsNullOrEmpty(json))
  132. {
  133. return null;
  134. }
  135. object obj;
  136. try
  137. {
  138. obj = JsonConvert.DeserializeObject(json, this._serializerSettings);
  139. }
  140. catch (JsonSerializationException ex)
  141. {
  142. throw new System.Runtime.Serialization.SerializationException(ex.Message, ex);
  143. }
  144. // If the object is a JToken we want to
  145. // convert it to dynamic, it if is any
  146. // other type we just return it.
  147. var jToken = obj as JToken;
  148. if (jToken != null)
  149. {
  150. return ConvertJTokenToDictionary(jToken);
  151. }
  152. else
  153. {
  154. return obj;
  155. }
  156. }
  157. /// <summary>
  158. /// Converts the <see cref="JToken"/> to <see cref="object"/>
  159. /// </summary>
  160. /// <param name="token">
  161. /// The token.
  162. /// </param>
  163. /// <returns>
  164. /// Returns the object.
  165. /// </returns>
  166. private static object ConvertJTokenToDictionary(JToken token)
  167. {
  168. if (token == null)
  169. {
  170. return null;
  171. }
  172. var jValue = token as JValue;
  173. if (jValue != null)
  174. {
  175. return jValue.Value;
  176. }
  177. var jContainer = token as JArray;
  178. if (jContainer != null)
  179. {
  180. var jsonList = new JsonArray();
  181. foreach (JToken arrayItem in jContainer)
  182. {
  183. jsonList.Add(ConvertJTokenToDictionary(arrayItem));
  184. }
  185. return jsonList;
  186. }
  187. var jsonObject = new JsonObject();
  188. var jsonDict = (IDictionary<string, object>)jsonObject;
  189. (from childToken in token where childToken is JProperty select childToken as JProperty).ToList().ForEach(property => jsonDict.Add(property.Name, ConvertJTokenToDictionary(property.Value)));
  190. return jsonObject;
  191. }
  192. }
  193. }