示例#1
0
        public void ShouldSerializeExample()
        {
            Employee joe = new Employee();

            joe.Name = "Joe Employee";
            Employee mike = new Employee();

            mike.Name = "Mike Manager";

            joe.Manager  = mike;
            mike.Manager = mike;

            string json = JsonConvert.SerializeObject(new[] { joe, mike }, Formatting.Indented);

            // [
            //   {
            //     "Name": "Joe Employee",
            //     "Manager": {
            //       "Name": "Mike Manager"
            //     }
            //   },
            //   {
            //     "Name": "Mike Manager"
            //   }
            // ]

            StringAssert.AreEqual(@"[
  {
    ""Name"": ""Joe Employee"",
    ""Manager"": {
      ""Name"": ""Mike Manager""
    }
  },
  {
    ""Name"": ""Mike Manager""
  }
]", json);
        }
        public void JTokenToString()
        {
            string json = @"{
  CPU: 'Intel',
  Drives: [
    'DVD read/writer',
    ""500 gigabyte hard drive""
  ]
}";

            JObject o = JObject.Parse(json);

            StringAssert.AreEqual(@"{
  ""CPU"": ""Intel"",
  ""Drives"": [
    ""DVD read/writer"",
    ""500 gigabyte hard drive""
  ]
}", o.ToString());

            JArray list = o.Value <JArray>("Drives");

            StringAssert.AreEqual(@"[
  ""DVD read/writer"",
  ""500 gigabyte hard drive""
]", list.ToString());

            JProperty cpuProperty = o.Property("CPU");

            Assert.AreEqual(@"""CPU"": ""Intel""", cpuProperty.ToString());

            JProperty drivesProperty = o.Property("Drives");

            StringAssert.AreEqual(@"""Drives"": [
  ""DVD read/writer"",
  ""500 gigabyte hard drive""
]", drivesProperty.ToString());
        }
        public void SerializeReferenceInDictionary()
        {
            EmployeeReference e1 = new EmployeeReference {
                Name = "e1"
            };
            EmployeeReference e2 = new EmployeeReference {
                Name = "e2"
            };

            Dictionary <string, EmployeeReference> employees = new Dictionary <string, EmployeeReference>
            {
                { "One", e1 },
                { "Two", e2 },
                { "Three", e1 },
                { "Four", e2 }
            };

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

            StringAssert.AreEqual(@"{
  ""One"": {
    ""$id"": ""1"",
    ""Name"": ""e1"",
    ""Manager"": null
  },
  ""Two"": {
    ""$id"": ""2"",
    ""Name"": ""e2"",
    ""Manager"": null
  },
  ""Three"": {
    ""$ref"": ""1""
  },
  ""Four"": {
    ""$ref"": ""2""
  }
}", json);
        }
示例#4
0
        public void ExtensionDataTest_SerializeWithNamingStrategy_Disabled()
        {
            ExtensionDataTestClass c = new ExtensionDataTestClass()
            {
                ExtensionData = new Dictionary <string, JToken>
                {
                    ["TestValue1"]       = 1,
                    ["alreadyCamelCase"] = new JObject
                    {
                        ["NotProcessed"] = true
                    }
                }
            };

            string json = JsonConvert.SerializeObject(c, new JsonSerializerSettings
            {
                ContractResolver = new Mapbox.Json.Serialization.DefaultContractResolver
                {
                    NamingStrategy = new Mapbox.Json.Serialization.CamelCaseNamingStrategy()
                },
                Formatting = Formatting.Indented
            });

            StringAssert.AreEqual(@"{
  ""readonly"": ""Readonly"",
  ""name"": null,
  ""custom_name"": null,
  ""getPrivate"": false,
  ""getOnly"": true,
  ""ints"": [
    0
  ],
  ""TestValue1"": 1,
  ""alreadyCamelCase"": {
    ""NotProcessed"": true
  }
}", json);
        }
示例#5
0
        public void Example()
        {
            #region Usage
            JavaScriptSettings settings = new JavaScriptSettings
            {
                OnLoadFunction   = new JRaw("OnLoad"),
                OnUnloadFunction = new JRaw("function(e) { alert(e); }")
            };

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

            Console.WriteLine(json);
            // {
            //   "OnLoadFunction": OnLoad,
            //   "OnUnloadFunction": function(e) { alert(e); }
            // }
            #endregion

            StringAssert.AreEqual(@"{
  ""OnLoadFunction"": OnLoad,
  ""OnUnloadFunction"": function(e) { alert(e); }
}", json);
        }
        public void Example()
        {
            #region Usage
            User user = new User
            {
                UserName = @"domain\username",
                Status   = UserStatus.Deleted
            };

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

            Console.WriteLine(json);
            // {
            //   "UserName": "******",
            //   "Status": "Deleted"
            // }
            #endregion

            StringAssert.AreEqual(@"{
  ""UserName"": ""domain\\username"",
  ""Status"": ""Deleted""
}", json);
        }
        public void SerializeDynamicObjectWithDefaultValueHandlingIgnore()
        {
            dynamic o = new TestDynamicObject();

            o.Text               = "Text!";
            o.Int                = int.MaxValue;
            o.IntDefault         = 0;
            o.NUllableIntDefault = default(int?);
            o.ChildObject        = null; // Tests an explicitly defined property of a dynamic object with a null value.
            o.DynamicChildObject = null; // vs. a completely dynamic defined property.

            string json = JsonConvert.SerializeObject(o, Formatting.Indented, new JsonSerializerSettings
            {
                DefaultValueHandling = DefaultValueHandling.Ignore,
            });

            Console.WriteLine(json);

            StringAssert.AreEqual(@"{
  ""Text"": ""Text!"",
  ""Int"": 2147483647
}", json);
        }
        public void GenerateForNullableInt32()
        {
            JsonSchemaGenerator jsonSchemaGenerator = new JsonSchemaGenerator();

            JsonSchema jsonSchema = jsonSchemaGenerator.Generate(typeof(NullableInt32TestClass));
            string     json       = jsonSchema.ToString();

            StringAssert.AreEqual(
                @"{
  ""type"": ""object"",
  ""properties"": {
    ""Value"": {
      ""required"": true,
      ""type"": [
        ""integer"",
        ""null""
      ]
    }
  }
}",
                json
                );
        }
示例#9
0
        public void CamelCaseTextFlagEnumSerialization()
        {
            EnumContainer <FlagsTestEnum> c = new EnumContainer <FlagsTestEnum>
            {
                Enum = FlagsTestEnum.First | FlagsTestEnum.Second
            };

#pragma warning disable CS0618 // Type or member is obsolete
            string json = JsonConvert.SerializeObject(
                c,
                Formatting.Indented,
                new StringEnumConverter {
                CamelCaseText = true
            }
                );
#pragma warning restore CS0618 // Type or member is obsolete
            StringAssert.AreEqual(
                @"{
  ""Enum"": ""first, second""
}",
                json
                );
        }
            internal static void SerializeVersionClass(string version1, string version2)
            {
                VersionClass versionClass = new VersionClass(version1, version2);

                string json = JsonConvert.SerializeObject(
                    versionClass,
                    Formatting.Indented,
                    new VersionConverter()
                    );

                string expectedJson = string.Format(
                    @"{{
  ""StringProperty1"": ""StringProperty1"",
  ""Version1"": ""{0}"",
  ""Version2"": ""{1}"",
  ""StringProperty2"": ""StringProperty2""
}}",
                    version1,
                    version2
                    );

                StringAssert.AreEqual(expectedJson, json);
            }
        public void Example()
        {
            #region Usage
            Vessel vessel = new Vessel
            {
                Name  = "Red October",
                Class = "Typhoon"
            };

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

            Console.WriteLine(json);
            // {
            //   "Name": "Red October",
            //   "Class": "Typhoon"
            // }
            #endregion

            StringAssert.AreEqual(@"{
  ""Name"": ""Red October"",
  ""Class"": ""Typhoon""
}", json);
        }
        public async Task WriteTokenWithPropertyParentAsync()
        {
            JValue v = new JValue(1);

            JTokenWriter writer = new JTokenWriter();

            await writer.WriteStartObjectAsync();

            await writer.WritePropertyNameAsync("Prop1");

            await writer.WriteTokenAsync(v.CreateReader());

            Assert.AreEqual(WriteState.Object, writer.WriteState);

            await writer.WriteEndObjectAsync();

            StringAssert.AreEqual(
                @"{
  ""Prop1"": 1
}",
                writer.Token.ToString()
                );
        }
        public void SerializeSqlBinaryClass()
        {
            SqlBinaryClass sqlBinaryClass = new SqlBinaryClass();

            sqlBinaryClass.SqlBinary          = new SqlBinary(TestData);
            sqlBinaryClass.NullableSqlBinary1 = new SqlBinary(TestData);
            sqlBinaryClass.NullableSqlBinary2 = null;

            string json = JsonConvert.SerializeObject(
                sqlBinaryClass,
                Formatting.Indented,
                new BinaryConverter()
                );

            StringAssert.AreEqual(
                @"{
  ""SqlBinary"": ""VGhpcyBpcyBzb21lIHRlc3QgZGF0YSEhIQ=="",
  ""NullableSqlBinary1"": ""VGhpcyBpcyBzb21lIHRlc3QgZGF0YSEhIQ=="",
  ""NullableSqlBinary2"": null
}",
                json
                );
        }
示例#14
0
        public void Test()
        {
            Activities activities = new Activities();

            activities.List = new List <Activity> {
                new Activity {
                    Name = "An activity"
                }
            };

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

            // note that this has been reverted back in 11.0.2 because it is causing compat issues
            // https://github.com/JamesNK/Newtonsoft.Json/issues/1627
            StringAssert.AreEqual(
                @"[
  {
    ""Name"": ""An activity""
  }
]",
                json
                );
        }
示例#15
0
        public void JsonObjectNullValueHandlingIgnore()
        {
            var movie = new MovieWithJsonObjectNullValueHandlingIgnore
            {
                Name        = "Bad Boys III",
                Description = "It's no Bad Boys"
            };

            string ignored = JsonConvert.SerializeObject(
                movie,
                Formatting.Indented,
                new JsonSerializerSettings {
                NullValueHandling = NullValueHandling.Include
            }
                );

            // {
            //   "Name": "Bad Boys III",
            //   "Description": "It's no Bad Boys"
            // }

            StringAssert.AreEqual(MovieNullValueHandlingIgnoreExpectedResult, ignored);
        }
        public void WriteTo_PositionalItemsValidation_FalseWithItemsSchema()
        {
            JSchema schema = new JSchema();

            schema.Items.Add(new JSchema {
                Type = JSchemaType.String
            });

            StringWriter   writer     = new StringWriter();
            JsonTextWriter jsonWriter = new JsonTextWriter(writer);

            jsonWriter.Formatting = Formatting.Indented;

            schema.WriteTo(jsonWriter);

            string json = writer.ToString();

            StringAssert.AreEqual(@"{
  ""items"": {
    ""type"": ""string""
  }
}", json);
        }
示例#17
0
        public void WriteTo_ExclusiveMinimum_ExclusiveMaximum()
        {
            JSchema schema = new JSchema();

            schema.ExclusiveMinimum = true;
            schema.ExclusiveMaximum = true;
            schema.Minimum          = 100;
            schema.Maximum          = 101;

            StringWriter   writer     = new StringWriter();
            JsonTextWriter jsonWriter = new JsonTextWriter(writer);

            jsonWriter.Formatting = Formatting.Indented;

            schema.WriteTo(jsonWriter);

            string json = writer.ToString();

            StringAssert.AreEqual(@"{
  ""exclusiveMinimum"": 100.0,
  ""exclusiveMaximum"": 101.0
}", json);
        }
示例#18
0
        public void Example()
        {
            #region Usage
            Videogame starcraft = new Videogame
            {
                Name        = "Starcraft",
                ReleaseDate = new DateTime(1998, 1, 1)
            };

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

            Console.WriteLine(json);
            // {
            //   "name": "Starcraft",
            //   "release_date": "1998-01-01T00:00:00"
            // }
            #endregion

            StringAssert.AreEqual(@"{
  ""name"": ""Starcraft"",
  ""release_date"": ""1998-01-01T00:00:00""
}", json);
        }
示例#19
0
        public void ExtensionDataDeserializeWithNonDefaultConstructorTest()
        {
            ExtensionDataDeserializeWithNonDefaultConstructor c = new ExtensionDataDeserializeWithNonDefaultConstructor("Name!");

            c._extensionData = new Dictionary <string, JToken>
            {
                { "Key!", "Value!" }
            };

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

            StringAssert.AreEqual(@"{
  ""Name"": ""Name!"",
  ""Key!"": ""Value!""
}", json);

            var c2 = JsonConvert.DeserializeObject <ExtensionDataDeserializeWithNonDefaultConstructor>(json);

            Assert.AreEqual("Name!", c2.Name);
            Assert.IsNotNull(c2._extensionData);
            Assert.AreEqual(1, c2._extensionData.Count);
            Assert.AreEqual("Value!", (string)c2._extensionData["Key!"]);
        }
示例#20
0
        public void WriteDuplicatePropertyName()
        {
            JTokenWriter writer = new JTokenWriter();

            writer.WriteStartObject();

            writer.WritePropertyName("prop1");
            writer.WriteStartObject();
            writer.WriteEndObject();

            writer.WritePropertyName("prop1");
            writer.WriteStartArray();
            writer.WriteEndArray();

            writer.WriteEndObject();

            StringAssert.AreEqual(
                @"{
  ""prop1"": []
}",
                writer.Token.ToString()
                );
        }
        public void SerializeNameEnumTest()
        {
            EnumContainer <NamedEnum> c = new EnumContainer <NamedEnum>
            {
                Enum = NamedEnum.First
            };

            string json = JsonConvert.SerializeObject(c, Formatting.Indented, new StringEnumConverter());

            StringAssert.AreEqual(@"{
  ""Enum"": ""@first""
}", json);

            c = new EnumContainer <NamedEnum>
            {
                Enum = NamedEnum.Third
            };

            json = JsonConvert.SerializeObject(c, Formatting.Indented, new StringEnumConverter());
            StringAssert.AreEqual(@"{
  ""Enum"": ""Third""
}", json);
        }
        public async Task FileContainsClassAndPublicPropertiesButNoClassGrouping()
        {
            var profile = this.GetProfileForTesting();

            profile.ClassGrouping = string.Empty;

            var fileContents = "public class TestViewModel"
                               + Environment.NewLine + "{"
                               + Environment.NewLine + "    public string FirstProperty { get; set; }"
                               + Environment.NewLine + "    public string SecondProperty { get; set; }"
                               + Environment.NewLine + "}";

            (IFileSystemAbstraction fs, IVisualStudioAbstraction vsa) = this.GetCSAbstractions(fileContents);

            var sut = new DropHandlerLogic(DefaultTestLogger.Create(), vsa, fs, profile);

            var actual = await sut.ExecuteAsync("C:\\Tests\\SomeFile.cs", 8);

            var expected = "<TextBlock Text=\"FirstProperty\" />"
                           + Environment.NewLine + "        <TextBlock Text=\"SecondProperty\" />";

            StringAssert.AreEqual(expected, actual);
        }
        public void SerializeInvoice()
        {
            Invoice invoice = new Invoice
            {
                Company              = "Acme Ltd.",
                Amount               = 50.0m,
                Paid                 = false,
                FollowUpDays         = 30,
                FollowUpEmailAddress = string.Empty,
                PaidDate             = null
            };

            string included = JsonConvert.SerializeObject(invoice,
                                                          Formatting.Indented,
                                                          new JsonSerializerSettings {
            });

            StringAssert.AreEqual(@"{
  ""Company"": ""Acme Ltd."",
  ""Amount"": 50.0,
  ""Paid"": false,
  ""PaidDate"": null,
  ""FollowUpDays"": 30,
  ""FollowUpEmailAddress"": """"
}", included);

            string ignored = JsonConvert.SerializeObject(invoice,
                                                         Formatting.Indented,
                                                         new JsonSerializerSettings {
                DefaultValueHandling = DefaultValueHandling.Ignore
            });

            StringAssert.AreEqual(@"{
  ""Company"": ""Acme Ltd."",
  ""Amount"": 50.0
}", ignored);
        }
        public void SerializeCircularReference()
        {
            CircularReferenceClass c1 = new CircularReferenceClass {
                Name = "c1"
            };
            CircularReferenceClass c2 = new CircularReferenceClass {
                Name = "c2"
            };
            CircularReferenceClass c3 = new CircularReferenceClass {
                Name = "c3"
            };

            c1.Child = c2;
            c2.Child = c3;
            c3.Child = c1;

            string json = JsonConvert.SerializeObject(c1, Formatting.Indented, new JsonSerializerSettings
            {
                PreserveReferencesHandling = PreserveReferencesHandling.Objects
            });

            StringAssert.AreEqual(@"{
  ""$id"": ""1"",
  ""Name"": ""c1"",
  ""Child"": {
    ""$id"": ""2"",
    ""Name"": ""c2"",
    ""Child"": {
      ""$id"": ""3"",
      ""Name"": ""c3"",
      ""Child"": {
        ""$ref"": ""1""
      }
    }
  }
}", json);
        }
        public void SerializeKeyValuePairWithDataTableKey()
        {
            DataTable  table    = new DataTable();
            DataColumn idColumn = new DataColumn("id", typeof(int));

            idColumn.AutoIncrement = true;

            DataColumn itemColumn = new DataColumn("item");

            table.Columns.Add(idColumn);
            table.Columns.Add(itemColumn);

            DataRow r = table.NewRow();

            r["item"] = "item!";
            r.EndEdit();
            table.Rows.Add(r);

            KeyValuePair <DataTable, int> pair = new KeyValuePair <DataTable, int>(table, 1);
            string serializedpair = JsonConvert.SerializeObject(pair, Formatting.Indented);

            StringAssert.AreEqual(@"{
  ""Key"": [
    {
      ""id"": 0,
      ""item"": ""item!""
    }
  ],
  ""Value"": 1
}", serializedpair);

            var pair2 = (KeyValuePair <DataTable, int>)JsonConvert.DeserializeObject(serializedpair, typeof(KeyValuePair <DataTable, int>));

            Assert.AreEqual(1, pair2.Value);
            Assert.AreEqual(1, pair2.Key.Rows.Count);
            Assert.AreEqual("item!", pair2.Key.Rows[0]["item"]);
        }
        public void Generate_GenericDictionary()
        {
            JsonSchemaGenerator generator = new JsonSchemaGenerator();
            JsonSchema          schema    = generator.Generate(typeof(Dictionary <string, List <string> >));

            string json = schema.ToString();

            StringAssert.AreEqual(@"{
  ""type"": ""object"",
  ""additionalProperties"": {
    ""type"": [
      ""array"",
      ""null""
    ],
    ""items"": {
      ""type"": [
        ""string"",
        ""null""
      ]
    }
  }
}", json);

            Dictionary <string, List <string> > value = new Dictionary <string, List <string> >
            {
                { "HasValue", new List <string>()
                  {
                      "first", "second", null
                  } },
                { "NoValue", null }
            };

            string  valueJson = JsonConvert.SerializeObject(value, Formatting.Indented);
            JObject o         = JObject.Parse(valueJson);

            Assert.IsTrue(o.IsValid(schema));
        }
        public void WriteTo_Enum()
        {
            JsonSchema schema = JsonSchema.Parse(@"{
  ""description"":""Type"",
  ""type"":[""string"",""array""],
  ""items"":{},
  ""enum"":[""string"",""object"",""array"",""boolean"",""number"",""integer"",""null"",""any""]
}");

            StringWriter   writer     = new StringWriter();
            JsonTextWriter jsonWriter = new JsonTextWriter(writer);

            jsonWriter.Formatting = Formatting.Indented;

            schema.WriteTo(jsonWriter);

            string json = writer.ToString();

            StringAssert.AreEqual(@"{
  ""description"": ""Type"",
  ""type"": [
    ""string"",
    ""array""
  ],
  ""items"": {},
  ""enum"": [
    ""string"",
    ""object"",
    ""array"",
    ""boolean"",
    ""number"",
    ""integer"",
    ""null"",
    ""any""
  ]
}", json);
        }
示例#28
0
        public void DictionaryEvents()
        {
            SerializationEventTestDictionary obj = new SerializationEventTestDictionary
            {
                { 1.1m, "first" },
                { 2.222222222m, "second" },
                { int.MaxValue, "third" },
                { Convert.ToDecimal(Math.PI), "fourth" }
            };

            Assert.AreEqual(11, obj.Member1);
            Assert.AreEqual("Hello World!", obj.Member2);
            Assert.AreEqual("This is a nonserialized value", obj.Member3);
            Assert.AreEqual(null, obj.Member4);

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

            StringAssert.AreEqual(@"{
  ""1.1"": ""first"",
  ""2.222222222"": ""second"",
  ""2147483647"": ""third"",
  ""3.14159265358979"": ""fourth"",
  ""79228162514264337593543950335"": ""Inserted on serializing""
}", json);

            Assert.AreEqual(11, obj.Member1);
            Assert.AreEqual("This value was reset after serialization.", obj.Member2);
            Assert.AreEqual("This is a nonserialized value", obj.Member3);
            Assert.AreEqual(null, obj.Member4);

            obj = JsonConvert.DeserializeObject <SerializationEventTestDictionary>(json);

            Assert.AreEqual(11, obj.Member1);
            Assert.AreEqual("Hello World!", obj.Member2);
            Assert.AreEqual("This value was set during deserialization", obj.Member3);
            Assert.AreEqual("This value was set after deserialization.", obj.Member4);
        }
示例#29
0
        public void ListEvents()
        {
            SerializationEventTestList obj = new SerializationEventTestList
            {
                1.1m,
                2.222222222m,
                int.MaxValue,
                Convert.ToDecimal(Math.PI)
            };

            Assert.AreEqual(11, obj.Member1);
            Assert.AreEqual("Hello World!", obj.Member2);
            Assert.AreEqual("This is a nonserialized value", obj.Member3);
            Assert.AreEqual(null, obj.Member4);

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

            StringAssert.AreEqual(@"[
  -1.0,
  1.1,
  2.222222222,
  2147483647.0,
  3.14159265358979
]", json);

            Assert.AreEqual(11, obj.Member1);
            Assert.AreEqual("This value was reset after serialization.", obj.Member2);
            Assert.AreEqual("This is a nonserialized value", obj.Member3);
            Assert.AreEqual(null, obj.Member4);

            obj = JsonConvert.DeserializeObject <SerializationEventTestList>(json);

            Assert.AreEqual(11, obj.Member1);
            Assert.AreEqual("Hello World!", obj.Member2);
            Assert.AreEqual("This value was set during deserialization", obj.Member3);
            Assert.AreEqual("This value was set after deserialization.", obj.Member4);
        }
示例#30
0
        public void WriteTo_DisallowMultiple()
        {
            JsonSchema schema = JsonSchema.Parse(
                @"{
  ""description"":""Type"",
  ""type"":[""string"",""array""],
  ""items"":{},
  ""disallow"":[""string"",""object"",""array""]
}"
                );

            StringWriter   writer     = new StringWriter();
            JsonTextWriter jsonWriter = new JsonTextWriter(writer);

            jsonWriter.Formatting = Formatting.Indented;

            schema.WriteTo(jsonWriter);

            string json = writer.ToString();

            StringAssert.AreEqual(
                @"{
  ""description"": ""Type"",
  ""type"": [
    ""string"",
    ""array""
  ],
  ""items"": {},
  ""disallow"": [
    ""string"",
    ""object"",
    ""array""
  ]
}",
                json
                );
        }