1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
|
// Copyright (c) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
#if FEATURE_DYNAMIC
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Dynamic;
using System.IO;
using System.Json;
using System.Linq.Expressions;
namespace System.Runtime.Serialization.Json
{
/// <summary>
/// This class extends the functionality of the <see cref="JsonValue"/> type.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public static class JsonValueExtensions
{
/// <summary>
/// Creates a <see cref="System.Json.JsonValue"/> object based on an arbitrary CLR object.
/// </summary>
/// <param name="value">The object to be converted to <see cref="System.Json.JsonValue"/>.</param>
/// <returns>The <see cref="System.Json.JsonValue"/> which represents the given object.</returns>
/// <remarks>The conversion is done through the <see cref="System.Runtime.Serialization.Json.DataContractJsonSerializer"/>;
/// the object is first serialized into JSON using the serializer, then parsed into a <see cref="System.Json.JsonValue"/>
/// object.</remarks>
public static JsonValue CreateFrom(object value)
{
JsonValue jsonValue = null;
if (value != null)
{
jsonValue = value as JsonValue;
if (jsonValue == null)
{
jsonValue = JsonValueExtensions.CreatePrimitive(value);
if (jsonValue == null)
{
jsonValue = JsonValueExtensions.CreateFromDynamic(value);
if (jsonValue == null)
{
jsonValue = JsonValueExtensions.CreateFromComplex(value);
}
}
}
}
return jsonValue;
}
/// <summary>
/// Attempts to convert this <see cref="System.Json.JsonValue"/> instance into the type T.
/// </summary>
/// <typeparam name="T">The type to which the conversion is being performed.</typeparam>
/// <param name="jsonValue">The <see cref="JsonValue"/> instance this method extension is to be applied to.</param>
/// <param name="valueOfT">An instance of T initialized with this instance, or the default
/// value of T, if the conversion cannot be performed.</param>
/// <returns>true if this <see cref="System.Json.JsonValue"/> instance can be read as type T; otherwise, false.</returns>
public static bool TryReadAsType<T>(this JsonValue jsonValue, out T valueOfT)
{
if (jsonValue == null)
{
throw new ArgumentNullException("jsonValue");
}
object value;
if (JsonValueExtensions.TryReadAsType(jsonValue, typeof(T), out value))
{
valueOfT = (T)value;
return true;
}
valueOfT = default(T);
return false;
}
/// <summary>
/// Attempts to convert this <see cref="System.Json.JsonValue"/> instance into the type T.
/// </summary>
/// <typeparam name="T">The type to which the conversion is being performed.</typeparam>
/// <param name="jsonValue">The <see cref="JsonValue"/> instance this method extension is to be applied to.</param>
/// <returns>An instance of T initialized with the <see cref="System.Json.JsonValue"/> value
/// specified if the conversion.</returns>
/// <exception cref="System.NotSupportedException">If this <see cref="System.Json.JsonValue"/> value cannot be
/// converted into the type T.</exception>
[SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter",
Justification = "The generic parameter is used to specify the output type")]
public static T ReadAsType<T>(this JsonValue jsonValue)
{
if (jsonValue == null)
{
throw new ArgumentNullException("jsonValue");
}
return (T)JsonValueExtensions.ReadAsType(jsonValue, typeof(T));
}
/// <summary>
/// Attempts to convert this <see cref="System.Json.JsonValue"/> instance into the type T, returning a fallback value
/// if the conversion fails.
/// </summary>
/// <typeparam name="T">The type to which the conversion is being performed.</typeparam>
/// <param name="jsonValue">The <see cref="JsonValue"/> instance this method extension is to be applied to.</param>
/// <param name="fallback">A fallback value to be retuned in case the conversion cannot be performed.</param>
/// <returns>An instance of T initialized with the <see cref="System.Json.JsonValue"/> value
/// specified if the conversion succeeds or the specified fallback value if it fails.</returns>
public static T ReadAsType<T>(this JsonValue jsonValue, T fallback)
{
if (jsonValue == null)
{
throw new ArgumentNullException("jsonValue");
}
T outVal;
if (JsonValueExtensions.TryReadAsType<T>(jsonValue, out outVal))
{
return outVal;
}
return fallback;
}
/// <summary>
/// Attempts to convert this <see cref="System.Json.JsonValue"/> instance into an instance of the specified type.
/// </summary>
/// <param name="jsonValue">The <see cref="JsonValue"/> instance this method extension is to be applied to.</param>
/// <param name="type">The type to which the conversion is being performed.</param>
/// <returns>An object instance initialized with the <see cref="System.Json.JsonValue"/> value
/// specified if the conversion.</returns>
/// <exception cref="System.NotSupportedException">If this <see cref="System.Json.JsonValue"/> value cannot be
/// converted into the type T.</exception>
public static object ReadAsType(this JsonValue jsonValue, Type type)
{
if (jsonValue == null)
{
throw new ArgumentNullException("jsonValue");
}
if (type == null)
{
throw new ArgumentNullException("type");
}
object result;
if (JsonValueExtensions.TryReadAsType(jsonValue, type, out result))
{
return result;
}
throw new NotSupportedException(RS.Format(System.Json.Properties.Resources.CannotReadAsType, jsonValue.GetType().FullName, type.FullName));
}
/// <summary>
/// Attempts to convert this <see cref="System.Json.JsonValue"/> instance into an instance of the specified type.
/// </summary>
/// <param name="jsonValue">The <see cref="JsonValue"/> instance this method extension is to be applied to.</param>
/// <param name="type">The type to which the conversion is being performed.</param>
/// <param name="value">An object to be initialized with this instance or null if the conversion cannot be performed.</param>
/// <returns>true if this <see cref="System.Json.JsonValue"/> instance can be read as the specified type; otherwise, false.</returns>
[SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate",
Justification = "This is the non-generic version of the method.")]
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Exception translates to fail.")]
public static bool TryReadAsType(this JsonValue jsonValue, Type type, out object value)
{
if (jsonValue == null)
{
throw new ArgumentNullException("jsonValue");
}
if (type == null)
{
throw new ArgumentNullException("type");
}
if (type == typeof(JsonValue) || type == typeof(object))
{
value = jsonValue;
return true;
}
if (type == typeof(object[]) || type == typeof(Dictionary<string, object>))
{
if (!JsonValueExtensions.CanConvertToClrCollection(jsonValue, type))
{
value = null;
return false;
}
}
if (jsonValue.TryReadAs(type, out value))
{
return true;
}
try
{
using (MemoryStream ms = new MemoryStream())
{
jsonValue.Save(ms);
ms.Position = 0;
DataContractJsonSerializer dcjs = new DataContractJsonSerializer(type);
value = dcjs.ReadObject(ms);
}
return true;
}
catch (Exception)
{
value = null;
return false;
}
}
/// <summary>
/// Determines whether the specified <see cref="JsonValue"/> instance can be converted to the specified collection <see cref="Type"/>.
/// </summary>
/// <param name="jsonValue">The instance to be converted.</param>
/// <param name="collectionType">The collection type to convert the instance to.</param>
/// <returns>true if the instance can be converted, false otherwise</returns>
private static bool CanConvertToClrCollection(JsonValue jsonValue, Type collectionType)
{
if (jsonValue != null)
{
return (jsonValue.JsonType == JsonType.Object && collectionType == typeof(Dictionary<string, object>)) ||
(jsonValue.JsonType == JsonType.Array && collectionType == typeof(object[]));
}
return false;
}
private static JsonValue CreatePrimitive(object value)
{
JsonPrimitive jsonPrimitive;
if (JsonPrimitive.TryCreate(value, out jsonPrimitive))
{
return jsonPrimitive;
}
return null;
}
private static JsonValue CreateFromComplex(object value)
{
DataContractJsonSerializer dcjs = new DataContractJsonSerializer(value.GetType());
using (MemoryStream ms = new MemoryStream())
{
dcjs.WriteObject(ms, value);
ms.Position = 0;
return JsonValue.Load(ms);
}
}
[SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily", Justification = "value is not the same")]
private static JsonValue CreateFromDynamic(object value)
{
JsonObject parent = null;
DynamicObject dynObj = value as DynamicObject;
if (dynObj != null)
{
parent = new JsonObject();
Stack<CreateFromTypeStackInfo> infoStack = new Stack<CreateFromTypeStackInfo>();
IEnumerator<string> keys = null;
do
{
if (keys == null)
{
keys = dynObj.GetDynamicMemberNames().GetEnumerator();
}
while (keys.MoveNext())
{
JsonValue child = null;
string key = keys.Current;
SimpleGetMemberBinder binder = new SimpleGetMemberBinder(key);
if (dynObj.TryGetMember(binder, out value))
{
DynamicObject childDynObj = value as DynamicObject;
if (childDynObj != null)
{
child = new JsonObject();
parent.Add(key, child);
infoStack.Push(new CreateFromTypeStackInfo(parent, dynObj, keys));
parent = child as JsonObject;
dynObj = childDynObj;
keys = null;
break;
}
else
{
if (value != null)
{
child = value as JsonValue;
if (child == null)
{
child = JsonValueExtensions.CreatePrimitive(value);
if (child == null)
{
child = JsonValueExtensions.CreateFromComplex(value);
}
}
}
parent.Add(key, child);
}
}
}
if (infoStack.Count > 0 && keys != null)
{
CreateFromTypeStackInfo info = infoStack.Pop();
parent = info.JsonObject;
dynObj = info.DynamicObject;
keys = info.Keys;
}
}
while (infoStack.Count > 0);
}
return parent;
}
private class CreateFromTypeStackInfo
{
public CreateFromTypeStackInfo(JsonObject jsonObject, DynamicObject dynamicObject, IEnumerator<string> keyEnumerator)
{
JsonObject = jsonObject;
DynamicObject = dynamicObject;
Keys = keyEnumerator;
}
/// <summary>
/// Gets of sets
/// </summary>
public JsonObject JsonObject { get; set; }
/// <summary>
/// Gets of sets
/// </summary>
public DynamicObject DynamicObject { get; set; }
/// <summary>
/// Gets of sets
/// </summary>
public IEnumerator<string> Keys { get; set; }
}
private class SimpleGetMemberBinder : GetMemberBinder
{
public SimpleGetMemberBinder(string name)
: base(name, false)
{
}
public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, DynamicMetaObject errorSuggestion)
{
if (target != null && errorSuggestion == null)
{
string exceptionMessage = RS.Format(System.Json.Properties.Resources.DynamicPropertyNotDefined, target.LimitType, Name);
Expression throwExpression = Expression.Throw(Expression.Constant(new InvalidOperationException(exceptionMessage)), typeof(object));
errorSuggestion = new DynamicMetaObject(throwExpression, target.Restrictions);
}
return errorSuggestion;
}
}
}
}
#endif
|