Inheritance: IContractResolver
    public void ResolveProperties_IgnoreStatic()
    {
      var resolver = new DefaultContractResolver();
      var contract = (JsonObjectContract)resolver.ResolveContract(typeof(NumberFormatInfo));

      Assert.IsFalse(contract.Properties.Any(c => c.PropertyName == "InvariantInfo"));
    }
Example #2
1
        public void SerializeCompilerGeneratedMembers()
        {
            StructTest structTest = new StructTest
            {
              IntField = 1,
              IntProperty = 2,
              StringField = "Field",
              StringProperty = "Property"
            };

              DefaultContractResolver skipCompilerGeneratedResolver = new DefaultContractResolver
              {
            DefaultMembersSearchFlags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public
              };

              string skipCompilerGeneratedJson = JsonConvert.SerializeObject(structTest, Formatting.Indented,
            new JsonSerializerSettings { ContractResolver = skipCompilerGeneratedResolver });

              Assert.AreEqual(@"{
              ""StringField"": ""Field"",
              ""IntField"": 1,
              ""StringProperty"": ""Property"",
              ""IntProperty"": 2
            }", skipCompilerGeneratedJson);

              DefaultContractResolver includeCompilerGeneratedResolver = new DefaultContractResolver
              {
            DefaultMembersSearchFlags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public,
            SerializeCompilerGeneratedMembers = true
              };

              string includeCompilerGeneratedJson = JsonConvert.SerializeObject(structTest, Formatting.Indented,
            new JsonSerializerSettings { ContractResolver = includeCompilerGeneratedResolver });

              Assert.AreEqual(@"{
              ""StringField"": ""Field"",
              ""IntField"": 1,
              ""<StringProperty>k__BackingField"": ""Property"",
              ""<IntProperty>k__BackingField"": 2,
              ""StringProperty"": ""Property"",
              ""IntProperty"": 2
            }", includeCompilerGeneratedJson);
        }
        public void Example()
        {
            #region Usage
            User user1 = new User
            {
                UserName = "******",
                Enabled = true
            };

            DefaultContractResolver contractResolver = new DefaultContractResolver
            {
                NamingStrategy = new CamelCaseNamingStrategy()
            };

            string json = JsonConvert.SerializeObject(user1, new JsonSerializerSettings
            {
                ContractResolver = contractResolver,
                Formatting = Formatting.Indented
            });

            Console.WriteLine(json);
            // {
            //   "userName": "******",
            //   "enabled": true
            // }
            #endregion

            StringAssert.AreEqual(@"{
  ""userName"": ""jamesn"",
  ""enabled"": true
}", json);
        }
    public void DeserializeDataMemberClassWithNoDataContract()
    {
      var resolver = new DefaultContractResolver();
      var contract = (JsonObjectContract)resolver.ResolveContract(typeof(AddressWithDataMember));

      Assert.AreEqual("AddressLine1", contract.Properties[0].PropertyName);
    }
        public void SerializeUsingInternalConverter()
        {
            DefaultContractResolver contractResolver = new DefaultContractResolver();
            JsonObjectContract contract = (JsonObjectContract)contractResolver.ResolveContract(typeof(KeyValuePair<string, int>));

            Assert.AreEqual(typeof(KeyValuePairConverter), contract.InternalConverter.GetType());

            IList<KeyValuePair<string, int>> values = new List<KeyValuePair<string, int>>
            {
                new KeyValuePair<string, int>("123", 123),
                new KeyValuePair<string, int>("456", 456)
            };

            string json = JsonConvert.SerializeObject(values, Formatting.Indented);

            StringAssert.AreEqual(@"[
  {
    ""Key"": ""123"",
    ""Value"": 123
  },
  {
    ""Key"": ""456"",
    ""Value"": 456
  }
]", json);

            IList<KeyValuePair<string, int>> v2 = JsonConvert.DeserializeObject<IList<KeyValuePair<string, int>>>(json);

            Assert.AreEqual(2, v2.Count);
            Assert.AreEqual("123", v2[0].Key);
            Assert.AreEqual(123, v2[0].Value);
            Assert.AreEqual("456", v2[1].Key);
            Assert.AreEqual(456, v2[1].Value);
        }
Example #6
0
 public DocumentConvention()
 {
     FindIdentityProperty = q => q.Name == "Id";
     FindTypeTagName = t => DefaultTypeTagName(t);
     JsonContractResolver = new DefaultContractResolver(shareCache: true);
     MaxNumberOfRequestsPerSession = 30;
 }
Example #7
0
        /// <summary>
        /// Constructorul principal care seteaza variabila readonly _responseValue serializata in metoda SerializeToStreamAsync si optional si contractResolver folosit pentru serializare
        /// </summary>
        /// <param name="responseValue">Obiectul care va fi serializat si scris in Stream de metoda SerializeToStreamAsync</param>
        /// <param name="contractResolver">Daca parametrul este null sau nespecificat se foloseste o instanta noua de tip DefaultContractResolver</param>
        public JsonContent(object responseValue, IContractResolver contractResolver = null)
        {
            _responseValue = responseValue;
            if (contractResolver == null)
                contractResolver = new DefaultContractResolver();
            _contractResolver = contractResolver;

            Headers.ContentType = new MediaTypeHeaderValue("application/json");
        }
		public DocumentConvention()
		{
			FindIdentityProperty = q => q.Name == "Id";
			FindTypeTagName = t => DefaultTypeTagName(t);
			IdentityPartsSeparator = "/";
		    JsonContractResolver = new DefaultContractResolver(shareCache: true);
		    MaxNumberOfRequestsPerSession = 30;
			CustomizeJsonSerializer = serializer => { };
		}
Example #9
0
 public RelationContractResolver(DefaultContractResolver original, DocumentConvention documentConvention, IEnumerable<Type> rootTypes)
     : base(true)
 {
     _rootTypes = new HashSet<Type>();
     _referenceConverter = new ReferenceConverter(documentConvention);
     foreach (var rootType in rootTypes)
     {
         _rootTypes.Add(rootType);
     }
     DefaultMembersSearchFlags = original.DefaultMembersSearchFlags;
 }
        public static JsonSerializer CreateDefaultSerializer()
        {
            DefaultContractResolver resolver = new DefaultContractResolver();
            // allow json.net to use private setter
            resolver.DefaultMembersSearchFlags |= System.Reflection.BindingFlags.NonPublic;

            return new JsonSerializer
            {
                TypeNameHandling = TypeNameHandling.Objects,
                ContractResolver = resolver
            };
        }
Example #11
0
        protected void InitializeCluster(IContractResolver contractResolver = null)
        {
            if (contractResolver == null)
            {
                contractResolver = new DefaultContractResolver();
            }

            var config = new ClientConfiguration();
            config.Servers.Add(new Uri("http://127.0.0.1:8091"));
            config.DeserializationSettings.ContractResolver = contractResolver;
            config.SerializationSettings.ContractResolver = contractResolver;
            ClusterHelper.Initialize(config);
        }
        public void Example()
        {
            #region Usage
            DailyHighScores dailyHighScores = new DailyHighScores
            {
                Date = new DateTime(2016, 6, 27, 0, 0, 0, DateTimeKind.Utc),
                Game = "Donkey Kong",
                UserPoints = new Dictionary<string, int>
                {
                    ["JamesNK"] = 9001,
                    ["JoC"] = 1337,
                    ["JessicN"] = 1000
                }
            };

            DefaultContractResolver contractResolver = new DefaultContractResolver
            {
                NamingStrategy = new CamelCaseNamingStrategy
                {
                    ProcessDictionaryKeys = false
                }
            };

            string json = JsonConvert.SerializeObject(dailyHighScores, new JsonSerializerSettings
            {
                ContractResolver = contractResolver,
                Formatting = Formatting.Indented
            });

            Console.WriteLine(json);
            // {
            //   "date": "2016-06-27T00:00:00Z",
            //   "game": "Donkey Kong",
            //   "userPoints": {
            //     "JamesNK": 9001,
            //     "JoC": 1337,
            //     "JessicN": 1000
            //   }
            // }
            #endregion

            StringAssert.AreEqual(@"{
  ""date"": ""2016-06-27T00:00:00Z"",
  ""game"": ""Donkey Kong"",
  ""userPoints"": {
    ""JamesNK"": 9001,
    ""JoC"": 1337,
    ""JessicN"": 1000
  }
}", json);
        }
        public static JsonSerializer CreateDefaultSerializer()
        {
            var resolver = new DefaultContractResolver();

            // allow json.net to use private setter
            resolver.DefaultMembersSearchFlags |= BindingFlags.NonPublic;

            return new JsonSerializer
            {
                TypeNameHandling = TypeNameHandling.Objects,
                MissingMemberHandling = MissingMemberHandling.Error, // catch possible deserialization errors
                ContractResolver = resolver
            };
        }
        public void SerializeUsingInternalConverter()
        {
            DefaultContractResolver contractResolver = new DefaultContractResolver();
            JsonObjectContract contract = (JsonObjectContract) contractResolver.ResolveContract(typeof (KeyValuePair<string, int>));

            Assert.AreEqual(typeof(KeyValuePairConverter), contract.InternalConverter.GetType());

            IList<KeyValuePair<string, int>> values = new List<KeyValuePair<string, int>>
            {
                new KeyValuePair<string, int>("123", 123),
                new KeyValuePair<string, int>("456", 456)
            };

            string json = JsonConvert.SerializeObject(values, Formatting.Indented);

            Console.WriteLine(json);
        }
    public void AddPropertyIncludesPrivateImplementations()
    {
      var value = new PrivateImplementationBClass
        {
          OverriddenProperty = "OverriddenProperty",
          PropertyA = "PropertyA",
          PropertyB = "PropertyB"
        };

      var resolver = new DefaultContractResolver();
      var contract = (JsonObjectContract) resolver.ResolveContract(value.GetType());

      Assert.AreEqual(3, contract.Properties.Count);
      Assert.IsTrue(contract.Properties.Contains("OverriddenProperty"), "Contract is missing property 'OverriddenProperty'");
      Assert.IsTrue(contract.Properties.Contains("PropertyA"), "Contract is missing property 'PropertyA'");
      Assert.IsTrue(contract.Properties.Contains("PropertyB"), "Contract is missing property 'PropertyB'");
    }
Example #16
0
        static void CountingLockTest()
        {
            Console.WriteLine("\n Newtonsoft.Json.Serialization.DefaultContractResolver");
            var resolver = new Newtonsoft.Json.Serialization.DefaultContractResolver();

            WriteProps((JsonObjectContract)resolver.ResolveContract(typeof(CountingLock)));

            Console.WriteLine("\n Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver");
            var r = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver();

            WriteProps((JsonObjectContract)r.ResolveContract(typeof(CountingLock)));

            Console.WriteLine("\n System.Net.Http.Formatting.JsonContractResolver");
            var resolv = new System.Net.Http.Formatting.JsonContractResolver(new Formatter());

            WriteProps((JsonObjectContract)resolv.ResolveContract(typeof(CountingLock)));
        }
Example #17
0
        protected virtual JsonContract CreateContract(Type objectType)
        {
            Type type = ReflectionUtils.EnsureNotNullableType(objectType);

            if (JsonConvert.IsJsonPrimitiveType(type))
            {
                return(this.CreatePrimitiveContract(type));
            }
            if (JsonTypeReflector.GetJsonObjectAttribute(type) != null)
            {
                return(this.CreateObjectContract(type));
            }
            if (JsonTypeReflector.GetJsonArrayAttribute(type) != null)
            {
                return(this.CreateArrayContract(type));
            }
            if (type == typeof(JToken) || type.IsSubclassOf(typeof(JToken)))
            {
                return(this.CreateLinqContract(type));
            }
            if (CollectionUtils.IsDictionaryType(type))
            {
                return(this.CreateDictionaryContract(type));
            }
            if (typeof(IEnumerable).IsAssignableFrom(type))
            {
                return(this.CreateArrayContract(type));
            }
            if (DefaultContractResolver.CanConvertToString(type))
            {
                return(this.CreateStringContract(type));
            }
            if (typeof(ISerializable).IsAssignableFrom(type))
            {
                return(this.CreateISerializableContract(type));
            }
            return(this.CreateObjectContract(type));
        }
Example #18
0
 private void GetCallbackMethodsForType(Type type, out MethodInfo onSerializing, out MethodInfo onSerialized, out MethodInfo onDeserializing, out MethodInfo onDeserialized, out MethodInfo onError)
 {
     onSerializing   = null;
     onSerialized    = null;
     onDeserializing = null;
     onDeserialized  = null;
     onError         = null;
     MethodInfo[] methods = type.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
     for (int i = 0; i < (int)methods.Length; i++)
     {
         MethodInfo methodInfo = methods[i];
         if (!methodInfo.ContainsGenericParameters)
         {
             Type            type1      = null;
             ParameterInfo[] parameters = methodInfo.GetParameters();
             if (DefaultContractResolver.IsValidCallback(methodInfo, parameters, typeof(OnSerializingAttribute), onSerializing, ref type1))
             {
                 onSerializing = methodInfo;
             }
             if (DefaultContractResolver.IsValidCallback(methodInfo, parameters, typeof(OnSerializedAttribute), onSerialized, ref type1))
             {
                 onSerialized = methodInfo;
             }
             if (DefaultContractResolver.IsValidCallback(methodInfo, parameters, typeof(OnDeserializingAttribute), onDeserializing, ref type1))
             {
                 onDeserializing = methodInfo;
             }
             if (DefaultContractResolver.IsValidCallback(methodInfo, parameters, typeof(OnDeserializedAttribute), onDeserialized, ref type1))
             {
                 onDeserialized = methodInfo;
             }
             if (DefaultContractResolver.IsValidCallback(methodInfo, parameters, typeof(OnErrorAttribute), onError, ref type1))
             {
                 onError = methodInfo;
             }
         }
     }
 }
        public void Example()
        {
            #region Usage
            User user = new User
            {
                FirstName = "John",
                LastName = "Smith",
                Upn = "*****@*****.**"
            };

            DefaultContractResolver contractResolver = new DefaultContractResolver
            {
                NamingStrategy = new CamelCaseNamingStrategy
                {
                    OverrideSpecifiedNames = false
                }
            };

            string json = JsonConvert.SerializeObject(user, new JsonSerializerSettings
            {
                ContractResolver = contractResolver,
                Formatting = Formatting.Indented
            });

            Console.WriteLine(json);
            // {
            //   "firstName": "John",
            //   "lastName": "Smith",
            //   "UPN": "*****@*****.**"
            // }
            #endregion

            StringAssert.AreEqual(@"{
  ""firstName"": ""John"",
  ""lastName"": ""Smith"",
  ""UPN"": ""*****@*****.**""
}", json);
        }
 private void GetCallbackMethodsForType(Type type, out MethodInfo onSerializing, out MethodInfo onSerialized, out MethodInfo onDeserializing, out MethodInfo onDeserialized, out MethodInfo onError)
 {
     onSerializing   = null;
     onSerialized    = null;
     onDeserializing = null;
     onDeserialized  = null;
     onError         = null;
     MethodInfo[] methods = type.GetMethods(54);
     for (int i = 0; i < methods.Length; i++)
     {
         MethodInfo methodInfo = methods[i];
         if (!methodInfo.get_ContainsGenericParameters())
         {
             Type            type2      = null;
             ParameterInfo[] parameters = methodInfo.GetParameters();
             if (DefaultContractResolver.IsValidCallback(methodInfo, parameters, typeof(OnSerializingAttribute), onSerializing, ref type2))
             {
                 onSerializing = methodInfo;
             }
             if (DefaultContractResolver.IsValidCallback(methodInfo, parameters, typeof(OnSerializedAttribute), onSerialized, ref type2))
             {
                 onSerialized = methodInfo;
             }
             if (DefaultContractResolver.IsValidCallback(methodInfo, parameters, typeof(OnDeserializingAttribute), onDeserializing, ref type2))
             {
                 onDeserializing = methodInfo;
             }
             if (DefaultContractResolver.IsValidCallback(methodInfo, parameters, typeof(OnDeserializedAttribute), onDeserialized, ref type2))
             {
                 onDeserialized = methodInfo;
             }
             if (DefaultContractResolver.IsValidCallback(methodInfo, parameters, typeof(OnErrorAttribute), onError, ref type2))
             {
                 onError = methodInfo;
             }
         }
     }
 }
Example #21
0
 private void GetCallbackMethodsForType(Type type, out MethodInfo onSerializing, out MethodInfo onSerialized, out MethodInfo onDeserializing, out MethodInfo onDeserialized, out MethodInfo onError)
 {
     onSerializing   = (MethodInfo)null;
     onSerialized    = (MethodInfo)null;
     onDeserializing = (MethodInfo)null;
     onDeserialized  = (MethodInfo)null;
     onError         = (MethodInfo)null;
     foreach (MethodInfo method in type.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
     {
         if (!method.ContainsGenericParameters)
         {
             Type            prevAttributeType = (Type)null;
             ParameterInfo[] parameters        = method.GetParameters();
             if (DefaultContractResolver.IsValidCallback(method, parameters, typeof(OnSerializingAttribute), onSerializing, ref prevAttributeType))
             {
                 onSerializing = method;
             }
             if (DefaultContractResolver.IsValidCallback(method, parameters, typeof(OnSerializedAttribute), onSerialized, ref prevAttributeType))
             {
                 onSerialized = method;
             }
             if (DefaultContractResolver.IsValidCallback(method, parameters, typeof(OnDeserializingAttribute), onDeserializing, ref prevAttributeType))
             {
                 onDeserializing = method;
             }
             if (DefaultContractResolver.IsValidCallback(method, parameters, typeof(OnDeserializedAttribute), onDeserialized, ref prevAttributeType))
             {
                 onDeserialized = method;
             }
             if (DefaultContractResolver.IsValidCallback(method, parameters, typeof(OnErrorAttribute), onError, ref prevAttributeType))
             {
                 onError = method;
             }
         }
     }
 }
        public void WhenSerializationErrorDetectedBySerializer_ThenCallbackIsCalled()
        {
            // Verify contract is properly finding our callback
            var resolver = new DefaultContractResolver().ResolveContract(typeof(FooEvent));

#pragma warning disable 612,618
            Debug.Assert(resolver.OnError != null);
            Debug.Assert(resolver.OnError == typeof(FooEvent).GetMethod("OnError", BindingFlags.Instance | BindingFlags.NonPublic));
#pragma warning restore 612,618

            var serializer = JsonSerializer.Create(new JsonSerializerSettings
            {
                // If I don't specify Error here, the callback isn't called
                // either, but no exception is thrown.
                MissingMemberHandling = MissingMemberHandling.Error,
            });

            // This throws with missing member exception, rather than calling my callback.
            var foo = serializer.Deserialize<FooEvent>(new JsonTextReader(new StringReader("{ Id: 25 }")));

            // When fixed, this would pass.
            Debug.Assert(foo.Identifier == 25);
        }
Example #23
0
		private static JsonSerializer CreateSerializer()
		{
			// TODO: converters could be cached for speedup

			var ser = new JsonSerializer
			{
				TypeNameHandling = TypeNameHandling.Auto,
				PreserveReferencesHandling = PreserveReferencesHandling.All, // leaving out Array is a very important problem, and means that we can't rely on a directly shared array to work.
				ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
			};

			ser.Converters.Add(new TypeTypeConverter(new[]
			{
				// all expected Types to convert are either in this assembly or mscorlib
				typeof(Machine).Assembly,
				typeof(object).Assembly
			}));
			
			ser.Converters.Add(new DelegateConverter());
			ser.Converters.Add(new ArrayConverter());

			var cr = new DefaultContractResolver();
			cr.DefaultMembersSearchFlags |= System.Reflection.BindingFlags.NonPublic;
			ser.ContractResolver = cr;

			return ser;
		}
 static RequestNotifications()
 {
     ContractResolver = new DefaultContractResolver();
 }
        public void ParametrizedCreator()
        {
            var resolver = new DefaultContractResolver();
            var contract = (JsonObjectContract)resolver.ResolveContract(typeof(PublicParametizedConstructorWithPropertyNameConflictWithAttribute));

            Assert.IsNull(contract.DefaultCreator);
            Assert.IsNotNull(contract.ParametrizedCreator);
#pragma warning disable 618
            Assert.AreEqual(contract.ParametrizedConstructor, typeof(PublicParametizedConstructorWithPropertyNameConflictWithAttribute).GetConstructor(new[] { typeof(string) }));
#pragma warning restore 618
            Assert.AreEqual(1, contract.CreatorParameters.Count);
            Assert.AreEqual("name", contract.CreatorParameters[0].PropertyName);

#pragma warning disable 618
            contract.ParametrizedConstructor = null;
#pragma warning restore 618
            Assert.IsNull(contract.ParametrizedCreator);
        }
        public void OverrideCreator()
        {
            var resolver = new DefaultContractResolver();
            var contract = (JsonObjectContract)resolver.ResolveContract(typeof(MultipleParamatrizedConstructorsJsonConstructor));

            Assert.IsNull(contract.DefaultCreator);
            Assert.IsNotNull(contract.OverrideCreator);
#pragma warning disable 618
            Assert.AreEqual(contract.OverrideConstructor, typeof(MultipleParamatrizedConstructorsJsonConstructor).GetConstructor(new[] { typeof(string), typeof(int) }));
#pragma warning restore 618
            Assert.AreEqual(2, contract.CreatorParameters.Count);
            Assert.AreEqual("Value", contract.CreatorParameters[0].PropertyName);
            Assert.AreEqual("Age", contract.CreatorParameters[1].PropertyName);

#pragma warning disable 618
            contract.OverrideConstructor = null;
#pragma warning restore 618
            Assert.IsNull(contract.OverrideCreator);
        }
        public void CustomOverrideCreator()
        {
            var resolver = new DefaultContractResolver();
            var contract = (JsonObjectContract)resolver.ResolveContract(typeof(MultipleParamatrizedConstructorsJsonConstructor));

            bool ensureCustomCreatorCalled = false;

            contract.OverrideCreator = args =>
            {
                ensureCustomCreatorCalled = true;
                return new MultipleParamatrizedConstructorsJsonConstructor((string) args[0], (int) args[1]);
            };
#pragma warning disable 618
            Assert.IsNull(contract.OverrideConstructor);
#pragma warning restore 618

            var o = JsonConvert.DeserializeObject<MultipleParamatrizedConstructorsJsonConstructor>("{Value:'value!', Age:1}", new JsonSerializerSettings
            {
                ContractResolver = resolver
            });

            Assert.AreEqual("value!", o.Value);
            Assert.AreEqual(1, o.Age);
            Assert.IsTrue(ensureCustomCreatorCalled);
        }
 private ModelFilterContext FilterContextFor(Type type)
 {
     var jsonObjectContract = new DefaultContractResolver().ResolveContract(type);
     return new ModelFilterContext(type, (jsonObjectContract as JsonObjectContract), null);
 }
        public virtual void ProcessRequest(HttpContext context)
        {
            try
            {
                var values = new Dictionary<string, object>();

                var ct = context.Request.ContentType + ';';
                ct = ct.Substring(0, ct.IndexOf(';'));
                switch (ct)
                {
                    case "application/json":
                        FillParamsFromJson(context, values);
                        break;

                    case "application/x-www-form-urlencoded":
                        FillParamsFromForm(context, values);
                        break;
                }

                var expression = values.Count == 0
                                     ? _method + "()"
                                     : string.Format("{0}(#{1})", _method, string.Join(", #", values.Keys));

                var temp = ExpressionEvaluator.GetValue(_target, expression, values);
                var isXml = new List<string>(context.Request.AcceptTypes ?? new[] {"text/xml"})
                    .Contains("text/xml");

                var result = new {success = true, result = temp};
                var memory = new MemoryStream();

                if (isXml)
                {
                    new XmlSerializer(result.GetType()).Serialize(memory, result);
                    context.Response.ContentType = "text/xml";
                }
                else
                {
                    var contract = new DefaultContractResolver();
                    if (temp != null)
                    {
                        var type = temp.GetType().IsGenericType
                                       ? temp.GetType().GetGenericArguments()[0]
                                       : temp.GetType();
                        
                        contract = new CustomContractResolver(type);

                        var managed = temp as IManagedSerializable;
                        if (managed != null)
                            ((CustomContractResolver) contract).AddTypes(managed.SerializedTypes);
                    }

                    var jsonSett = new JsonSerializerSettings
                        {
                            DateTimeZoneHandling = DateTimeZoneHandling.Local,
                            ContractResolver = contract,
                            ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                        };
                    
                    var writer = new StreamWriter(memory);
                    writer.Write(JsonConvert.SerializeObject(result, jsonSett));
                    writer.Flush();

                    context.Response.ContentType = "application/json";
                }

                context.Response.AddHeader("Content-Encoding", "gzip");
                context.Response.Filter = new GZipStream(context.Response.Filter, CompressionMode.Compress);
                context.Response.OutputStream.Write(memory.GetBuffer(), 0, (int)memory.Length);
            }
            catch (Exception ex)
            {
                var result = new { success = false, message = ex.Message };
                var memory = new MemoryStream();

                var writer = new StreamWriter(memory);
                writer.Write(JsonConvert.SerializeObject(result));
                writer.Flush();

                context.Response.StatusCode = 500;
                context.Response.ContentType = "application/json";
                context.Response.OutputStream.Write(memory.GetBuffer(), 0, (int)memory.Length);
            }
        }
Example #30
0
 public JsonPatchDocument()
 {
     Operations = new List<Operation>();
     ContractResolver = new DefaultContractResolver();
 }
 private static bool IsValidCallback(MethodInfo method, ParameterInfo[] parameters, Type attributeType, MethodInfo currentCallback, ref Type prevAttributeType)
 {
     if (!method.IsDefined(attributeType, false))
     {
         return(false);
     }
     if (currentCallback != null)
     {
         throw new Exception("Invalid attribute. Both '{0}' and '{1}' in type '{2}' have '{3}'.".FormatWith(CultureInfo.InvariantCulture, new object[]
         {
             method,
             currentCallback,
             DefaultContractResolver.GetClrTypeFullName(method.DeclaringType),
             attributeType
         }));
     }
     if (prevAttributeType != null)
     {
         throw new Exception("Invalid Callback. Method '{3}' in type '{2}' has both '{0}' and '{1}'.".FormatWith(CultureInfo.InvariantCulture, new object[]
         {
             prevAttributeType,
             attributeType,
             DefaultContractResolver.GetClrTypeFullName(method.DeclaringType),
             method
         }));
     }
     if (method.IsVirtual)
     {
         throw new Exception("Virtual Method '{0}' of type '{1}' cannot be marked with '{2}' attribute.".FormatWith(CultureInfo.InvariantCulture, new object[]
         {
             method,
             DefaultContractResolver.GetClrTypeFullName(method.DeclaringType),
             attributeType
         }));
     }
     if (method.ReturnType != typeof(void))
     {
         throw new Exception("Serialization Callback '{1}' in type '{0}' must return void.".FormatWith(CultureInfo.InvariantCulture, new object[]
         {
             DefaultContractResolver.GetClrTypeFullName(method.DeclaringType),
             method
         }));
     }
     if (attributeType == typeof(OnErrorAttribute))
     {
         if (parameters == null || parameters.Length != 2 || parameters[0].ParameterType != typeof(StreamingContext) || parameters[1].ParameterType != typeof(ErrorContext))
         {
             throw new Exception("Serialization Error Callback '{1}' in type '{0}' must have two parameters of type '{2}' and '{3}'.".FormatWith(CultureInfo.InvariantCulture, new object[]
             {
                 DefaultContractResolver.GetClrTypeFullName(method.DeclaringType),
                 method,
                 typeof(StreamingContext),
                 typeof(ErrorContext)
             }));
         }
     }
     else if (parameters == null || parameters.Length != 1 || parameters[0].ParameterType != typeof(StreamingContext))
     {
         throw new Exception("Serialization Callback '{1}' in type '{0}' must have a single parameter of type '{2}'.".FormatWith(CultureInfo.InvariantCulture, new object[]
         {
             DefaultContractResolver.GetClrTypeFullName(method.DeclaringType),
             method,
             typeof(StreamingContext)
         }));
     }
     prevAttributeType = attributeType;
     return(true);
 }
Example #32
0
        private MemberInfo GetExtensionDataMemberForType(Type type)
        {
            IEnumerable <MemberInfo> source = this.GetClassHierarchyForType(type).SelectMany(delegate(Type baseType)
            {
                IList <MemberInfo> list = new List <MemberInfo>();
                list.AddRange(baseType.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic));
                list.AddRange(baseType.GetFields(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic));
                return(list);
            });

            return(source.LastOrDefault(delegate(MemberInfo m)
            {
                MemberTypes memberTypes = m.MemberType();
                if (memberTypes != MemberTypes.Property && memberTypes != MemberTypes.Field)
                {
                    return false;
                }
                if (!m.IsDefined(typeof(JsonExtensionDataAttribute), false))
                {
                    return false;
                }
                Type memberUnderlyingType = ReflectionUtils.GetMemberUnderlyingType(m);
                Type type2;
                if (ReflectionUtils.ImplementsGenericDefinition(memberUnderlyingType, typeof(IDictionary <, >), out type2))
                {
                    Type type3 = type2.GetGenericArguments()[0];
                    Type type4 = type2.GetGenericArguments()[1];
                    if (type3.IsAssignableFrom(typeof(string)) && type4.IsAssignableFrom(typeof(JToken)))
                    {
                        return true;
                    }
                }
                throw new JsonException("Invalid extension data attribute on '{0}'. Member '{1}' type must implement IDictionary<string, JToken>.".FormatWith(CultureInfo.InvariantCulture, DefaultContractResolver.GetClrTypeFullName(m.DeclaringType), m.Name));
            }));
        }