From ae07b9f14140288f2d3cd60d56430acbb2dfc2bc Mon Sep 17 00:00:00 2001 From: "Benjamin S. Berman" Date: Thu, 11 Feb 2016 17:50:34 -0800 Subject: [PATCH] Add support for Unity types --- JsonFx/TypeCoercionUtility.cs | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/JsonFx/TypeCoercionUtility.cs b/JsonFx/TypeCoercionUtility.cs index a87f4e6..aec3cff 100755 --- a/JsonFx/TypeCoercionUtility.cs +++ b/JsonFx/TypeCoercionUtility.cs @@ -26,11 +26,13 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \*---------------------------------------------------------------------------------*/ + #endregion License using System; using System.Collections; using System.Collections.Generic; +using System.Runtime.Serialization; using System.ComponentModel; using System.Globalization; using System.Reflection; @@ -127,23 +129,33 @@ internal object ProcessTypeHint( internal Object InstantiateObject(Type objectType, out Dictionary memberMap) { - if (objectType.IsInterface || objectType.IsAbstract || objectType.IsValueType) + if (objectType.IsInterface || objectType.IsAbstract) { throw new JsonTypeCoercionException( String.Format(TypeCoercionUtility.ErrorCannotInstantiate, objectType.FullName)); } ConstructorInfo ctor = objectType.GetConstructor(Type.EmptyTypes); + Object result = null; + if (ctor == null) { - throw new JsonTypeCoercionException( - String.Format(TypeCoercionUtility.ErrorDefaultCtor, objectType.FullName)); + if (objectType.IsValueType) { + try { + result = FormatterServices.GetUninitializedObject(objectType); + } catch { + throw new JsonTypeCoercionException( + String.Format(TypeCoercionUtility.ErrorCannotInstantiate, objectType.FullName)); + } + } else { + throw new JsonTypeCoercionException( + String.Format(TypeCoercionUtility.ErrorDefaultCtor, objectType.FullName)); + } } - Object result; try { // always try-catch Invoke() to expose real exception - result = ctor.Invoke(null); + result = result ?? ctor.Invoke(null); } catch (TargetInvocationException ex) {