当前位置: 首页>>代码示例>>C#>>正文


C# JsonSerializerSettings类代码示例

本文整理汇总了C#中JsonSerializerSettings的典型用法代码示例。如果您正苦于以下问题:C# JsonSerializerSettings类的具体用法?C# JsonSerializerSettings怎么用?C# JsonSerializerSettings使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


JsonSerializerSettings类属于命名空间,在下文中一共展示了JsonSerializerSettings类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: SerializationExample

        private static void SerializationExample(IEnumerable<IItem> items)
        {
            // 1.
            /*    Console.WriteLine(JsonConvert.SerializeObject(items));

            // 2.
            Console.WriteLine(JsonConvert.SerializeObject(items, Formatting.Indented));
            */
            // 3.
            var settings = new JsonSerializerSettings() { Formatting = Formatting.Indented,
                TypeNameHandling = TypeNameHandling.Auto };
            Console.WriteLine(JsonConvert.SerializeObject(items, settings));

            // 4.
            var text = JsonConvert.SerializeObject(items, settings);
            var desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            var filename = Path.Combine(desktop, "items.json");
            File.WriteAllText(filename, text);

            // 5.

            var textFromFile = File.ReadAllText(filename);
            var itemsFromFile = JsonConvert.DeserializeObject<IItem[]>(textFromFile, settings);
            var currency = Currency.EUR;
            foreach (var x in itemsFromFile)
                Console.WriteLine($"{x.Description.Truncate(50),-50} {x.Price.ConvertTo(currency).Amount,8:0.00} {currency}");
            SerializationExample.Run(items);
        }
开发者ID:rkerschbaumer,项目名称:oom,代码行数:28,代码来源:Program.cs

示例2: PopulateExpandoObjectAsRoot

		public void PopulateExpandoObjectAsRoot()
		{
			dynamic library = new ExpandoObject();

			library.Name = "1Items";
			library.ArticleArray = new Article[] { new Article("Article1") };
			library.ArticleList = new List<Article>() { new Article("Article1") };
			library.ArticleIList = new List<Article>() { new Article("Article1") };
			library.ArticleCollection = new ArticleCollection() { new Article("Article1") };
			library.StringArray = new[] { "Article1" };

			Assert.AreEqual(1, library.ArticleArray.Length);
			Assert.AreEqual(1, library.ArticleCollection.Count);
			Assert.AreEqual(1, library.ArticleList.Count);
			Assert.AreEqual(1, library.ArticleList.Count);
			Assert.AreEqual(1, library.StringArray.Length);

			var settings = new JsonSerializerSettings
			{
				TypeNameHandling = TypeNameHandling.Auto
			};

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

			var expando = new ExpandoObject();
			JsonConvert.PopulateObject(json, expando, settings);
			dynamic result = expando;
			Assert.AreEqual(result.Name, library.Name);
			Assert.AreEqual(1, result.ArticleArray.Length);
			Assert.AreEqual(1, result.ArticleCollection.Count);
			Assert.AreEqual(1, result.ArticleList.Count);
			Assert.AreEqual(1, result.ArticleList.Count);
			Assert.AreEqual(1, result.StringArray.Length);
		}
开发者ID:taliesins,项目名称:Newtonsoft.Json,代码行数:34,代码来源:JsonListSerializationTests.cs

示例3: JsonNetResult

 public JsonNetResult(object data)
 {
     Data = data;
     SerializerSettings = new JsonSerializerSettings()
     {
         ReferenceLoopHandling = ReferenceLoopHandling.Serialize
     };
 }
开发者ID:JBonsink,项目名称:BaxterLicence,代码行数:8,代码来源:JsonNetResult.cs

示例4: CreateFrom

        public static JsonWriter CreateFrom(StreamWriter streamWriter, JsonSerializerSettings settings)
        {
            var jw = new JsonTextWriter(streamWriter);

            // reader/writer specific
            // unset values won't override reader/writer set values
            jw.Formatting = settings.Formatting;
            jw.DateFormatHandling = settings.DateFormatHandling;
            jw.DateTimeZoneHandling = settings.DateTimeZoneHandling;
            jw.DateFormatString = settings.DateFormatString;
            jw.FloatFormatHandling = settings.FloatFormatHandling;
            jw.StringEscapeHandling = settings.StringEscapeHandling;
            jw.Culture = settings.Culture;

            return jw;
        }
开发者ID:thehexgod,项目名称:BESSY-DB,代码行数:16,代码来源:JsonWriterFactory.cs

示例5: CreateFrom

        public static BsonWriter CreateFrom(Stream stream, JsonSerializerSettings settings)
        {
            var bw = new BsonWriter(stream);

            // reader/writer specific
            // unset values won't override reader/writer set values
            bw.Formatting = settings.Formatting;
            bw.DateFormatHandling = settings.DateFormatHandling;
            bw.DateTimeZoneHandling = settings.DateTimeZoneHandling;
            bw.DateFormatString = settings.DateFormatString;
            bw.FloatFormatHandling = settings.FloatFormatHandling;
            bw.StringEscapeHandling = settings.StringEscapeHandling;
            bw.Culture = settings.Culture;

            return bw;
        }
开发者ID:thehexgod,项目名称:BESSY-DB,代码行数:16,代码来源:BsonWriterFactory.cs

示例6: SerializeDeserialize_DictionaryContextContainsGuid_DeserializesItemAsGuid

        public void SerializeDeserialize_DictionaryContextContainsGuid_DeserializesItemAsGuid()
        {
            const string contextKey = "k1";
            var someValue = Guid.NewGuid();

            Dictionary<string, Guid> inputContext = new Dictionary<string, Guid>();
            inputContext.Add(contextKey, someValue);

            JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings()
            {
                Formatting = Formatting.Indented,
                TypeNameHandling = TypeNameHandling.All,
                SpecialPropertyHandling = SpecialPropertyHandling.ReadAhead
            };
            string serializedString = JsonConvert.SerializeObject(inputContext, jsonSerializerSettings);

            Console.WriteLine(serializedString);

            var deserializedObject = (Dictionary<string, Guid>)JsonConvert.DeserializeObject(serializedString, jsonSerializerSettings);

            Assert.AreEqual(someValue, deserializedObject[contextKey]);
        }
开发者ID:SeanmanX,项目名称:opandroid,代码行数:22,代码来源:SpecialPropertyHandlingTests.cs

示例7: DeserializeExpandoObjectAsRoot

		public void DeserializeExpandoObjectAsRoot()
		{
			dynamic library = new ExpandoObject();

			library.Name = "1Items";
			library.ArticleArray = new Article[] { new Article("Article1") };
			library.ArticleList = new List<Article>() { new Article("Article1") };
			library.ArticleIList = new List<Article>() { new Article("Article1") };
			library.ArticleCollection = new ArticleCollection() { new Article("Article1") };
			library.StringArray = new[] { "Article1" };

			Assert.AreEqual(1, library.ArticleArray.Length);
			Assert.AreEqual(1, library.ArticleCollection.Count);
			Assert.AreEqual(1, library.ArticleList.Count);
			Assert.AreEqual(1, library.ArticleList.Count);
			Assert.AreEqual(1, library.StringArray.Length);

			var settings = new JsonSerializerSettings
			{
				TypeNameHandling = TypeNameHandling.Auto
			};

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

			//TODO: Fix this
			//var document = JsonConvert.DeserializeXNode(json, "root", false);

			var result = JsonConvert.DeserializeObject<dynamic>(json, settings);

			Assert.AreEqual(result.Name, library.Name);
			Assert.AreEqual(1, result.ArticleArray.Length);
			Assert.AreEqual(1, result.ArticleCollection.Count);
			Assert.AreEqual(1, result.ArticleList.Count);
			Assert.AreEqual(1, result.ArticleList.Count);
			Assert.AreEqual(1, result.StringArray.Length);
		}
开发者ID:taliesins,项目名称:Newtonsoft.Json,代码行数:36,代码来源:JsonListSerializationTests.cs

示例8: SerializeDeserialize_DictionaryContextContainsGuid_DeserializesItemAsGuid

        public void SerializeDeserialize_DictionaryContextContainsGuid_DeserializesItemAsGuid()
        {
            const string contextKey = "k1";
            var someValue = new Guid("5dd2dba0-20c0-49f8-a054-1fa3b0a8d774");

            Dictionary<string, Guid> inputContext = new Dictionary<string, Guid>();
            inputContext.Add(contextKey, someValue);

            JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings()
            {
                Formatting = Formatting.Indented,
                TypeNameHandling = TypeNameHandling.All,
                MetadataPropertyHandling = MetadataPropertyHandling.ReadAhead
            };
            string serializedString = JsonConvert.SerializeObject(inputContext, jsonSerializerSettings);

            StringAssert.AreEqual(@"{
  ""$type"": ""System.Collections.Generic.Dictionary`2[[System.String, mscorlib],[System.Guid, mscorlib]], mscorlib"",
  ""k1"": ""5dd2dba0-20c0-49f8-a054-1fa3b0a8d774""
}", serializedString);

            var deserializedObject = (Dictionary<string, Guid>)JsonConvert.DeserializeObject(serializedString, jsonSerializerSettings);

            Assert.AreEqual(someValue, deserializedObject[contextKey]);
        }
开发者ID:j2jensen,项目名称:ravendb,代码行数:25,代码来源:MetadataPropertyHandlingTests.cs

示例9: TypeNameHandlingAuto

        public void TypeNameHandlingAuto()
        {
            var binder = new MyBinder();

            var settings = new JsonSerializerSettings
            {
                TypeNameHandling = TypeNameHandling.Auto,
                Binder = binder
            };

            Zoo zoo = new Zoo
            {
                Animals = new List<Animal>
                {
                    new Dog("Dog!")
                }
            };

            JsonSerializer serializer = JsonSerializer.Create(settings);

            MemoryStream ms = new MemoryStream();
            BsonWriter bsonWriter = new BsonWriter(ms);
            serializer.Serialize(bsonWriter, zoo);

            ms.Seek(0, SeekOrigin.Begin);

            var deserialized = serializer.Deserialize<Zoo>(new BsonReader(ms));

            Assert.AreEqual(1, deserialized.Animals.Count);
            Assert.AreEqual("Dog!", deserialized.Animals[0].Name);
            Assert.IsTrue(deserialized.Animals[0] is Dog);

#if !(NET20 || NET35)
            Assert.IsTrue(binder.BindToNameCalled);
#endif
            Assert.IsTrue(binder.BindToTypeCalled);
        }
开发者ID:Redth,项目名称:Newtonsoft.Json,代码行数:37,代码来源:BsonReaderTests.cs

示例10: Test2

        private static void Test2()
        {
            #if NETCORE

            //ProtoBufTest.Test();
            {
                object exobj = null;
                try
                {
                    var b = 3;
                    b = 0;
                    var c = 2 / b;
                }
                catch (Exception exs)
                {
                    exobj = exs;
                }
                //var ex = new Exception("test ex");
                var ex = exobj;
                //var ex = new ServiceTest.Contract.Product
                //{
                //	Id = 223,
                //	Name = "abc book",
                //	Category = "Book",
                //	ListDate = DateTime.Now,
                //	Price = 34,
                //	Tags = new List<string>
                //	{
                //		"book",
                //		"tech",
                //		"new"
                //	}
                //};

                {
                    try
                    {
                        var setting = new JsonSerializerSettings
                        {
                            Formatting = Formatting.Indented,
                            ContractResolver = new SerializeContractResolver()
                        };
                        var json = JsonConvert.SerializeObject(ex, setting);
                        Console.WriteLine(json);
                        var dex = JsonConvert.DeserializeObject(json, ex.GetType(), setting);
                    }
                    catch (Exception)
                    {
                        throw;
                    }
                }

                var dcs = new DataContractSerializer(ex.GetType());
                var ms = new MemoryStream();
                dcs.WriteObject(ms, ex);

                ms.Position = 0;
                var dex3 = dcs.ReadObject(ms);
                var xml = Encoding.UTF8.GetString(ms.ToArray());

                var jss = new System.Runtime.Serialization.Json.DataContractJsonSerializer(ex.GetType());
                var jsms = new MemoryStream();
                jss.WriteObject(jsms, ex);

                ms.Position = 0;
                var dexjs = dcs.ReadObject(ms);
                var jsss = Encoding.UTF8.GetString(ms.ToArray());

                var product = new ServiceTest.Contract.Product
                {
                    Id = 223,
                    Name = "abc book",
                    Category = "Book",
                    ListDate = DateTime.Now,
                    Price = 34,
                    Tags = new List<string>
                    {
                        "book",
                        "tech",
                        "new"
                    }
                };
                var xmlSeriaizer = new System.Xml.Serialization.XmlSerializer(product.GetType());
                var stringWriter = new StringWriter();
                //var xmlWriter = new XmlWriter();
                xmlSeriaizer.Serialize(stringWriter, (object)product);
            }
            #endif
        }
开发者ID:chrishaly,项目名称:RpcLite,代码行数:89,代码来源:SerializeTest.cs

示例11: AllowNonPublicDefaultConstructor

    public void AllowNonPublicDefaultConstructor()
    {
      var settings = new JsonSerializerSettings();
      settings.ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor;

      var json = @"{
  ""contributors"": null,
  ""retweeted"": false,
  ""text"": ""Guys SX4 diesel is launched.what are your plans?catch us at #facebook http://bit.ly/dV3H1a #auto #car #maruti #india #delhi"",
  ""in_reply_to_user_id_str"": null,
  ""retweet_count"": 0,
  ""geo"": null,
  ""id_str"": ""40678260320768000"",
  ""in_reply_to_status_id"": null,
  ""source"": ""<a href=\""http://www.tweetdeck.com\"" rel=\""nofollow\"">TweetDeck</a>"",
  ""created_at"": ""Thu Feb 24 07:43:47 +0000 2011"",
  ""place"": null,
  ""coordinates"": null,
  ""truncated"": false,
  ""favorited"": false,
  ""user"": {
    ""profile_background_image_url"": ""http://a1.twimg.com/profile_background_images/206944715/twitter_bg.jpg"",
    ""url"": ""http://bit.ly/dcFwWC"",
    ""screen_name"": ""marutisuzukisx4"",
    ""verified"": false,
    ""friends_count"": 45,
    ""description"": ""This is the Official Maruti Suzuki SX4 Twitter ID! Men are Back - mail us on social (at) sx4bymaruti (dot) com"",
    ""follow_request_sent"": null,
    ""time_zone"": ""Chennai"",
    ""profile_text_color"": ""333333"",
    ""location"": ""India"",
    ""notifications"": null,
    ""profile_sidebar_fill_color"": ""efefef"",
    ""id_str"": ""196143889"",
    ""contributors_enabled"": false,
    ""lang"": ""en"",
    ""profile_background_tile"": false,
    ""created_at"": ""Tue Sep 28 12:55:15 +0000 2010"",
    ""followers_count"": 117,
    ""show_all_inline_media"": true,
    ""listed_count"": 1,
    ""geo_enabled"": true,
    ""profile_link_color"": ""009999"",
    ""profile_sidebar_border_color"": ""eeeeee"",
    ""protected"": false,
    ""name"": ""Maruti Suzuki SX4"",
    ""statuses_count"": 637,
    ""following"": null,
    ""profile_use_background_image"": true,
    ""profile_image_url"": ""http://a3.twimg.com/profile_images/1170694644/Slide1_normal.JPG"",
    ""id"": 196143889,
    ""is_translator"": false,
    ""utc_offset"": 19800,
    ""favourites_count"": 0,
    ""profile_background_color"": ""131516""
  },
  ""in_reply_to_screen_name"": null,
  ""id"": 40678260320768000,
  ""in_reply_to_status_id_str"": null,
  ""in_reply_to_user_id"": null
}";

      DictionaryDynamicObject foo = JsonConvert.DeserializeObject<DictionaryDynamicObject>(json, settings);

      Assert.AreEqual(false, foo.Values["retweeted"]);
    }
开发者ID:Jessecar96,项目名称:Newtonsoft.Json,代码行数:66,代码来源:DynamicTests.cs

示例12: SerializeMultiValueEntityKey

        public void SerializeMultiValueEntityKey()
        {
            EntityKey e = new EntityKey("DataServicesTestDatabaseEntities.Folder",
                new List<EntityKeyMember>
                {
                    new EntityKeyMember("GuidId", new Guid("A4E8BA80-EB24-4591-BB1C-62D3AD83701E")),
                    new EntityKeyMember("IntId", int.MaxValue),
                    new EntityKeyMember("LongId", long.MaxValue),
                    new EntityKeyMember("StringId", "String!"),
                    new EntityKeyMember("DateTimeId", new DateTime(2000, 12, 10, 10, 50, 0, DateTimeKind.Utc))
                });

            JsonSerializerSettings settings = new JsonSerializerSettings
            {
                Formatting = Formatting.Indented,
                ContractResolver = new CamelCasePropertyNamesContractResolver()
            };

            string json = JsonConvert.SerializeObject(e, settings);

            StringAssert.AreEqual(@"{
  ""$id"": ""1"",
  ""entitySetName"": ""Folder"",
  ""entityContainerName"": ""DataServicesTestDatabaseEntities"",
  ""entityKeyValues"": [
    {
      ""key"": ""GuidId"",
      ""type"": ""System.Guid"",
      ""value"": ""a4e8ba80-eb24-4591-bb1c-62d3ad83701e""
    },
    {
      ""key"": ""IntId"",
      ""type"": ""System.Int32"",
      ""value"": ""2147483647""
    },
    {
      ""key"": ""LongId"",
      ""type"": ""System.Int64"",
      ""value"": ""9223372036854775807""
    },
    {
      ""key"": ""StringId"",
      ""type"": ""System.String"",
      ""value"": ""String!""
    },
    {
      ""key"": ""DateTimeId"",
      ""type"": ""System.DateTime"",
      ""value"": ""12/10/2000 10:50:00""
    }
  ]
}", json);

            EntityKey newKey = JsonConvert.DeserializeObject<EntityKey>(json);
            Assert.IsFalse(ReferenceEquals(e, newKey));

            Assert.AreEqual(5, newKey.EntityKeyValues.Length);
            Assert.AreEqual("GuidId", newKey.EntityKeyValues[0].Key);
            Assert.AreEqual(new Guid("A4E8BA80-EB24-4591-BB1C-62D3AD83701E"), newKey.EntityKeyValues[0].Value);
            Assert.AreEqual("IntId", newKey.EntityKeyValues[1].Key);
            Assert.AreEqual(int.MaxValue, newKey.EntityKeyValues[1].Value);
            Assert.AreEqual("LongId", newKey.EntityKeyValues[2].Key);
            Assert.AreEqual(long.MaxValue, newKey.EntityKeyValues[2].Value);
            Assert.AreEqual("StringId", newKey.EntityKeyValues[3].Key);
            Assert.AreEqual("String!", newKey.EntityKeyValues[3].Value);
            Assert.AreEqual("DateTimeId", newKey.EntityKeyValues[4].Key);
            Assert.AreEqual(new DateTime(2000, 12, 10, 10, 50, 0, DateTimeKind.Utc), newKey.EntityKeyValues[4].Value);
        }
开发者ID:JamesNK,项目名称:Newtonsoft.Json,代码行数:68,代码来源:EntitiesSerializationTests.cs

示例13: DeserializeDateTimeOffset

        public void DeserializeDateTimeOffset()
        {
            var settings = new JsonSerializerSettings();
            settings.DateParseHandling = DateParseHandling.DateTimeOffset;
            settings.Converters.Add(new IsoDateTimeConverter());

            // Intentionally use an offset that is unlikely in the real world,
            // so the test will be accurate regardless of the local time zone setting.
            var offset = new TimeSpan(2, 15, 0);
            var dto = new DateTimeOffset(2014, 1, 1, 0, 0, 0, 0, offset);

            var test = JsonConvert.DeserializeObject<DateTimeOffset>("\"2014-01-01T00:00:00+02:15\"", settings);

            Assert.AreEqual(dto, test);
            Assert.AreEqual(dto.ToString("o"), test.ToString("o"));
        }
开发者ID:b-bot-108,项目名称:brain-bot-111-b-bot-110-BND,代码行数:16,代码来源:IsoDateTimeConverterTests.cs

示例14: PopulateExpandoObjectAsAProperty

		public void PopulateExpandoObjectAsAProperty()
		{
			var container = new MagicContainer();
			container.Name = "Container1";
			container.Library = new ExpandoObject();

			container.Library.Name = "1Items";
			container.Library.ArticleArray = new Article[] { new Article("Article1") };
			container.Library.ArticleList = new List<Article>() { new Article("Article1") };
			container.Library.ArticleIList = new List<Article>() { new Article("Article1") };
			container.Library.ArticleCollection = new ArticleCollection() { new Article("Article1") };
			container.Library.StringArray = new[] { "Article1" };

			Assert.AreEqual(1, container.Library.ArticleArray.Length);
			Assert.AreEqual(1, container.Library.ArticleCollection.Count);
			Assert.AreEqual(1, container.Library.ArticleList.Count);
			Assert.AreEqual(1, container.Library.ArticleList.Count);
			Assert.AreEqual(1, container.Library.StringArray.Length);

			var settings = new JsonSerializerSettings { };

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

			MagicContainer result = new MagicContainer();
			JsonConvert.PopulateObject(json, result, settings);

			Assert.AreEqual(result.Library.Name, container.Library.Name);
			Assert.AreEqual(1, result.Library.ArticleArray.Length);
			Assert.AreEqual(1, result.Library.ArticleCollection.Count);
			Assert.AreEqual(1, result.Library.ArticleList.Count);
			Assert.AreEqual(1, result.Library.ArticleList.Count);
			Assert.AreEqual(1, result.Library.StringArray.Length);
		}
开发者ID:taliesins,项目名称:Newtonsoft.Json,代码行数:33,代码来源:JsonListSerializationTests.cs

示例15: WriteEndOnPropertyState2

        public void WriteEndOnPropertyState2()
        {
            JsonSerializerSettings settings = new JsonSerializerSettings();
            settings.Error += (obj, args) =>
            {
                args.ErrorContext.Handled = true;
            };

            var data = new List<ErrorPerson2>
        {
          new ErrorPerson2 {FirstName = "Scott", LastName = "Hanselman"},
          new ErrorPerson2 {FirstName = "Scott", LastName = "Hunter"},
          new ErrorPerson2 {FirstName = "Scott", LastName = "Guthrie"},
          new ErrorPerson2 {FirstName = "James", LastName = "Newton-King"},
        };

            Dictionary<string, IEnumerable<IErrorPerson2>> dictionary = data.GroupBy(person => person.FirstName).ToDictionary(group => @group.Key, group => @group.Cast<IErrorPerson2>());
            string output = JsonConvert.SerializeObject(dictionary, Formatting.None, settings);

            Assert.AreEqual(@"{""Scott"":[],""James"":[]}", output);
        }
开发者ID:TheHunter,项目名称:Newtonsoft.Json,代码行数:21,代码来源:SerializationErrorHandlingTests.cs


注:本文中的JsonSerializerSettings类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。