Ejemplo n.º 1
0
		public void Setup()
		{

			_testCommand = A.Fake<ICommand>();
			_publisher = A.Fake<IPublisher>();
			_compositeApp = A.Fake<ICompositeApp>();
			_registry = A.Fake<ICommandRegistry>();
			_formatter = A.Fake<IResponseFormatter>();
			_publicationRecord = A.Fake<ICommandPublicationRecord>();
			_jsonSerializer = new DefaultJsonSerializer();
			_xmlSerializer = new DefaultXmlSerializer();

			A.CallTo(() => _testCommand.Created).Returns(DateTime.MaxValue);
			A.CallTo(() => _testCommand.CreatedBy).Returns(new Guid("ba5f18dc-e287-4d9e-ae71-c6989b10d778"));
			A.CallTo(() => _testCommand.Identifier).Returns(new Guid("ba5f18dc-e287-4d9e-ae71-c6989b10d778"));
			A.CallTo(() => _formatter.Serializers).Returns(new List<ISerializer> { _jsonSerializer, _xmlSerializer });
			A.CallTo(() => _publicationRecord.Dispatched).Returns(true);
			A.CallTo(() => _publicationRecord.Error).Returns(false);
			A.CallTo(() => _publicationRecord.Completed).Returns(true);
			A.CallTo(() => _publicationRecord.Created).Returns(DateTime.MinValue);
			A.CallTo(() => _publicationRecord.MessageLocation).Returns(new Uri("http://localhost/fake/message"));
			A.CallTo(() => _publicationRecord.MessageType).Returns(typeof(IPublicationRecord));
			A.CallTo(() => _publicationRecord.CreatedBy).Returns(Guid.Empty);
			A.CallTo(() => _compositeApp.GetCommandForInputModel(A.Dummy<IInputModel>())).Returns(_testCommand);
			A.CallTo(() => _publisher.PublishMessage(A.Fake<ICommand>())).Returns(_publicationId);
			A.CallTo(() => _registry.GetPublicationRecord(_publicationId)).Returns(_publicationRecord);

			_euclidApi = new ApiModule(_compositeApp, _registry, _publisher);
		}
Ejemplo n.º 2
0
        /// <summary>
        /// Method that performs an HTTP GET and returns the Json deserialization
        /// of the content returned from the call.
        /// </summary>
        /// <param name="webRequest">The WebRequest object to be used for the call.</param>
        /// <returns>Json deserialization of the content returned from the call.</returns>
        public static Dictionary <string, object> GetUrlContent(WebRequest webRequest)
        {
            Stream          content        = webRequest.GetResponse().GetResponseStream();
            string          returnedText   = new StreamReader(content).ReadToEnd();
            IJsonSerializer JsonSerializer = new DefaultJsonSerializer();

            return(JsonSerializer.Deserialize <Dictionary <string, object> >(returnedText));
        }
Ejemplo n.º 3
0
 public ModQueries(ILogger <ModQueries> logger, IGameQueries nexusModsGameQueries, IDistributedCache cache, IHttpClientFactory httpClientFactory, DefaultJsonSerializer jsonSerializer)
 {
     _logger = logger ?? throw new ArgumentNullException(nameof(logger));
     _nexusModsGameQueries = nexusModsGameQueries ?? throw new ArgumentNullException(nameof(nexusModsGameQueries));
     _cache             = cache ?? throw new ArgumentNullException(nameof(cache));
     _httpClientFactory = httpClientFactory ?? throw new ArgumentNullException(nameof(httpClientFactory));
     _jsonSerializer    = jsonSerializer ?? throw new ArgumentNullException(nameof(jsonSerializer));
 }
Ejemplo n.º 4
0
 public void Can_deserialize_to_dynamic_single()
 {
     var serializer = new DefaultJsonSerializer();
     var response = new RestResponse<dynamic>();
     response.SetContent(SingleInput);
     var proxy = serializer.DeserializeDynamic(response);
     Assert.IsNotNull(proxy);
 }
Ejemplo n.º 5
0
 public void Can_deserialize_to_dynamic_collection()
 {
     var serializer = new DefaultJsonSerializer();
     var response = new RestResponse<JsonObject>();
     response.SetContent(DoubleInput);
     var proxy = serializer.DeserializeDynamic(response);
     Assert.IsNotNull(proxy);
 }
        public void EmptyConstructorCreatesDefaultValues()
        {
            var serializer = new DefaultJsonSerializer();

            serializer.Name.Should().Be("default");
            serializer.JsonSerializer.Should().NotBeNull();
            serializer.JsonSerializer.Formatting.Should().Be(Formatting.None);
        }
        public void SerializeToStringSerializesCorrectly()
        {
            var serializer = new DefaultJsonSerializer();

            var json = serializer.SerializeToString(_expectedItem, typeof(TypeForJsonSerializer));

            json.Should().Be(_expectedJson);
        }
Ejemplo n.º 8
0
        public JsonSerializerTest()
        {
            var options = A.Fake <IOptions <EasyCachingJsonSerializerOptions> >();

            A.CallTo(() => options.Value).Returns(new EasyCachingJsonSerializerOptions());

            _serializer = new DefaultJsonSerializer(options);
        }
Ejemplo n.º 9
0
        public void SerializeObject_without_type_serializes_to_json_using_DefaultSerializerSettings()
        {
            // If Default is being used then there should be new lines
            var dog = new Dog(5, "spud", FurColor.Brindle);

            var json = DefaultJsonSerializer.SerializeObject(dog);

            Assert.That(json, Is.EqualTo("{\r\n  \"name\": \"spud\",\r\n  \"furColor\": \"brindle\",\r\n  \"dogTag\": \"my name is spud\",\r\n  \"nickname\": null,\r\n  \"age\": 5\r\n}"));
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Startup"/> class.
        /// </summary>
        /// <param name="configuration">The configuration.</param>
        /// <param name="env">The hosting environment.</param>
        public Startup(IConfiguration configuration, IHostingEnvironment env)
        {
            Configuration      = configuration;
            HostingEnvironment = env;
            AppInfo            = new AppInfoFactory().Create(typeof(Program));
            Serializer         = new DefaultJsonSerializer();

            Configuration.GetSection("ApiOptions").Bind(ApiOptions);
        }
Ejemplo n.º 11
0
        public void DerializeJson_WithNeoErrors_ReturnsErrors()
        {
            var deserializer = new DefaultJsonSerializer(new DictionaryEntityCache());

            var retval = deserializer.Deserialize <CypherResponse <DeserializationTestClass> >(ErrorJson);

            Assert.IsNull(retval.Results);
            Assert.IsTrue(retval.Errors.Any());
        }
Ejemplo n.º 12
0
        public void Should_Decode_Token_To_Json_Encoded_String()
        {
            var jsonSerializer = new DefaultJsonSerializer();
            var expectedPayload = jsonSerializer.Serialize(customer);

            string decodedPayload = JsonWebToken.Decode(token, "ABC", false);

            Assert.Equal(expectedPayload, decodedPayload);
        }
Ejemplo n.º 13
0
        public void DeserializeFromStringDeserializesCorrectly()
        {
            var serializer = new DefaultJsonSerializer();

            var item = serializer.DeserializeFromString(_expectedJson, typeof(TypeForJsonSerializer)) as TypeForJsonSerializer;

            item.Should().NotBeNull();
            item.Should().BeEquivalentTo(_expectedItem);
        }
        public void PostUserDescription()
        {
            var container = AppBuilder.CreateContainer();

            using (WebApp.Start(Settings.Current.BaseURL, app => AppBuilder.BuildWithContainer(app, container, false))) {
                var repository = container.GetInstance <IEventRepository>();
                repository.RemoveAll();

                const string referenceId    = "fda94ff32921425ebb08b73df1d1d34c";
                const string badReferenceId = "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz";

                var statsCounter = container.GetInstance <IAppStatsClient>() as InMemoryAppStatsClient;
                Assert.NotNull(statsCounter);

                EnsureSampleData(container);

                var events = new List <Event> {
                    new Event {
                        Message = "Testing", ReferenceId = referenceId
                    }
                };
                var configuration = GetClient().Configuration;
                var serializer    = new DefaultJsonSerializer();

                var client      = new DefaultSubmissionClient();
                var description = new UserDescription {
                    EmailAddress = "*****@*****.**", Description = "Some description."
                };
                statsCounter.WaitForCounter(StatNames.EventsUserDescriptionErrors, work: () => {
                    var response = client.PostUserDescription(referenceId, description, configuration, serializer);
                    Assert.True(response.Success, response.Message);
                    Assert.Null(response.Message);
                });

                statsCounter.WaitForCounter(StatNames.EventsUserDescriptionProcessed, work: () => {
                    var response = client.PostEvents(events, configuration, serializer);
                    Assert.True(response.Success, response.Message);
                    Assert.Null(response.Message);
                });

                container.GetInstance <IElasticClient>().Refresh();
                var ev = repository.GetByReferenceId("537650f3b77efe23a47914f4", referenceId).FirstOrDefault();
                Assert.NotNull(ev);
                Assert.NotNull(ev.GetUserDescription());
                Assert.Equal(description.ToJson(), ev.GetUserDescription().ToJson());

                Assert.Equal(2, statsCounter.GetCount(StatNames.EventsUserDescriptionErrors));
                statsCounter.WaitForCounter(StatNames.EventsUserDescriptionErrors, work: () => {
                    var response = client.PostUserDescription(badReferenceId, description, configuration, serializer);
                    Assert.True(response.Success, response.Message);
                    Assert.Null(response.Message);
                });

                Assert.Equal(2, statsCounter.GetCount(StatNames.EventsUserDescriptionErrors));
            }
        }
        public void DeserializeString_IfJsonCanBeDeserialized_ReturnsCorrectObject <T>(string dateFormat, string json, T expected)
        {
            var serializer = new DefaultJsonSerializer {
                DateFormat = dateFormat
            };

            var actual = serializer.Deserialize <T>(json);

            AssertExtension.AreObjectsValuesEqual(expected, actual);
        }
Ejemplo n.º 16
0
        public void Can_deserialize_to_dynamic_single()
        {
            var serializer = new DefaultJsonSerializer();
            var response   = new RestResponse <JsonObject>();

            response.SetContent(SingleInput);
            var proxy = serializer.DeserializeDynamic(response);

            Assert.IsNotNull(proxy);
        }
        public void Serialize_ReturnsCorrectJson <T>(string dateFormat, NamingStrategy enumNamingStrategy, T item, string expected)
        {
            var serializer = new DefaultJsonSerializer(enumNamingStrategy)
            {
                DateFormat = dateFormat
            };

            var actual = serializer.Serialize(item);

            AssertExtension.AreObjectsValuesEqual(expected, actual);
        }
Ejemplo n.º 18
0
        public async Task StartAsync(string port)
        {
            if (_isDisposed)
                throw new ObjectDisposedException(nameof(NetGameServer));

            if (_rpcServer != null)
                throw new InvalidOperationException();

            var serializer = new DefaultJsonSerializer(typeof(NetGameServer).GetTypeInfo().Assembly, Serialization.JsonSerializationSettings);
            _rpcServer = await RpcServer.StartAsync(port, this, serializer);
        }
Ejemplo n.º 19
0
        public void DeserializeObject_without_type_deserializes_json_into_JObject_using_DefaultSerializerSettings()
        {
            var dogJson = "{\"name\":\"Barney\",\"furColor\":\"brindle\",\"age\":10}";

            var dog = DefaultJsonSerializer.DeserializeObject(dogJson) as JObject;

            Assert.That(dog.Properties().Count(), Is.EqualTo(3));
            Assert.That(dog["name"].ToString(), Is.EqualTo("Barney"));
            Assert.That(dog["age"].ToString(), Is.EqualTo("10"));
            Assert.That(dog["furColor"].ToString(), Is.EqualTo("brindle"));
        }
Ejemplo n.º 20
0
        public void ConstructorPassesValuesCorrectly()
        {
            var serializer = new DefaultJsonSerializer("notdefault", new JsonSerializerSettings()
            {
                Formatting = Formatting.Indented
            });

            serializer.Name.Should().Be("notdefault");
            serializer.JsonSerializer.Should().NotBeNull();
            serializer.JsonSerializer.Formatting.Should().Be(Formatting.Indented);
        }
        public void DeserializeString_IfJsonCannotBeDeserialized_ThrowsException <T>(string dateFormat, string json, T defaultWithDeserializedType)
        {
            var serializer = new DefaultJsonSerializer {
                DateFormat = dateFormat
            };

            Assert.Catch(() =>
            {
                var actual = serializer.Deserialize <T>(json);
            });
        }
        public void CanRoundtripToJson()
        {
            var serializer = new DefaultJsonSerializer();
            var originalData = new Data { Message = "test", Number = 42, Assertion = true };

            string serializedData = serializer.Serialize(originalData);
            var deserializedData = serializer.Deserialize<Data>(serializedData);

            Assert.That(deserializedData.Message, Is.EqualTo(originalData.Message));
            Assert.That(deserializedData.Number, Is.EqualTo(originalData.Number));
            Assert.That(deserializedData.Assertion, Is.EqualTo(originalData.Assertion));
        }
Ejemplo n.º 23
0
        public void DerializeJson_EntitiesOnly_ReturnsCollectionOfEntities()
        {
            var deserializer = new DefaultJsonSerializer(new DictionaryEntityCache());

            var retval = deserializer.Deserialize <CypherResponse <DeserializationTestClass> >(Json);

            Assert.AreEqual(retval.Results.Count(), 2);
            dynamic actor = retval.Results.Select(r => r.Actor).First();

            Assert.AreEqual(actor.age, 33);
            Assert.AreEqual(actor.name, "mark");
        }
        public void DeserializeRestResponse_IfJsonCanBeDeserialized_ReturnsCorrectObject <T>(string dateFormat, string json, T expected)
        {
            var response = new RestResponse <T> {
                Content = json
            };
            var serializer = new DefaultJsonSerializer {
                DateFormat = dateFormat
            };

            var actual = serializer.Deserialize <T>(response);

            AssertExtension.AreObjectsValuesEqual(expected, actual);
        }
Ejemplo n.º 25
0
        public DefaultJsonSerializerTests()
        {
            var environment =
                new DefaultNancyEnvironment();

            environment.Tracing(
                enabled: true,
                displayErrorTraces: true);
            environment.Json();
            environment.Globalization(new[] { "en-US" });

            this.jsonSerializer = new DefaultJsonSerializer(environment);
        }
Ejemplo n.º 26
0
        public async Task JoinAsync(NetGameServerInfo serverInfo)
        {
            var serializer = new DefaultJsonSerializer(typeof(NetGameClient).GetTypeInfo().Assembly, Serialization.JsonSerializationSettings);
            _rpcClient = await RpcClient.ConnectAsync(serverInfo.RemoteAddress, serverInfo.RemotePort, this, serializer);

            JoinResult joinResult = await _rpcClient.Server.JoinAsync(PlayerInfo);
            var serverStub = new ClientSideServerProxy(_rpcClient.Connection);

            if (joinResult.IsSuccessful)
                await InitializeAsync(joinResult.SpawnPosition, serverStub);
            else
                throw new InvalidOperationException("Failed to join game server");
        }
Ejemplo n.º 27
0
        public DefaultJsonSerializerTests()
        {
            var environment =
                new DefaultNancyEnvironment();

            environment.Tracing(
                enabled: true,
                displayErrorTraces: true);
            environment.Json();
            environment.Globalization(new[] { "en-US" });

            this.jsonSerializer = new DefaultJsonSerializer(environment);
        }
Ejemplo n.º 28
0
        public void DeserializeObject_with_type_deserializes_json_using_DefaultSerializerSettings()
        {
            // If Default is being used then strict constructor matching will result in a Dog and not a Mouse
            var dogJson = "{\"name\":\"Barney\",\"furColor\":\"brindle\",\"age\":10}";

            var dog = DefaultJsonSerializer.DeserializeObject(dogJson, typeof(Animal)) as Dog;

            Assert.That(dog, Is.Not.Null);
            Assert.That(dog.Name, Is.EqualTo("Barney"));
            Assert.That(dog.Age, Is.EqualTo(10));
            Assert.That(dog.FurColor, Is.EqualTo(FurColor.Brindle));
            Assert.That(dog.DogTag, Is.EqualTo("my name is Barney"));
        }
Ejemplo n.º 29
0
        public void SerializeToStreamSerializesCorrectly()
        {
            var serializer = new DefaultJsonSerializer();

            using var stream = new MemoryStream();
            serializer.SerializeToStream(stream, _expectedItem, typeof(TypeForJsonSerializer));

            using var streamReader = new StreamReader(stream);
            stream.Seek(0, SeekOrigin.Begin);
            var json = streamReader.ReadToEnd();

            json.Should().Be(_expectedJson);
        }
Ejemplo n.º 30
0
        public void Can_deserialize_all_test_cases()
        {
            var serializer = new DefaultJsonSerializer();
            var files = Directory.GetFiles("Json", "*.json");
            foreach(var file in files)
            {
                var json = File.ReadAllText(file);
                var response = new RestResponse<dynamic>();
                response.SetContent(json);

                var proxy = serializer.DeserializeDynamic(response);
                Assert.IsNotNull(proxy);
            }
        }
Ejemplo n.º 31
0
        public void GetSettingsAsync()
        {
            using (WebApp.Start(Settings.Current.BaseURL, AppBuilder.Build)) {
                var configuration = ExceptionlessConfiguration.CreateDefault();
                var serializer    = new DefaultJsonSerializer();

                var client   = new DefaultSubmissionClient();
                var response = client.GetSettings(configuration, serializer);
                Assert.True(response.Success, response.Message);
                Assert.NotEqual(-1, response.SettingsVersion);
                Assert.NotNull(response.Settings);
                Assert.Null(response.Message);
            }
        }
Ejemplo n.º 32
0
        /// <summary>
        /// 将对象序列化成缩进结构的JSON,便于日志记录
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ToDumpJson(this object obj)
        {
            if (obj == null)
            {
                return("null");
            }

            DefaultJsonSerializer  serializer = ObjectFactory.New <DefaultJsonSerializer>();
            JsonSerializerSettings settings   = serializer.GetJsonSerializerSettings(true);

            // 设置为缩进格式
            settings.Formatting = Formatting.Indented;
            return(serializer.Serialize(obj, settings));
        }
Ejemplo n.º 33
0
        public void Should_camel_case_property_names_by_default()
        {
            // Given
            var sut = new DefaultJsonSerializer();
            var input = new { FirstName = "Joe", lastName = "Doe" };

            // When
            var output = new MemoryStream();
            sut.Serialize("application/json", input, output);
            var actual = Encoding.UTF8.GetString(output.ToArray());

            // Then
            actual.ShouldEqual("{\"firstName\":\"Joe\",\"lastName\":\"Doe\"}");
        }
        public void DeserializeRestResponse_IfJsonCannotBeDeserialized_ThrowsException <T>(string dateFormat, string json, T defaultWithDeserializedType)
        {
            var response = new RestResponse <T> {
                Content = json
            };
            var serializer = new DefaultJsonSerializer {
                DateFormat = dateFormat
            };

            Assert.Catch(() =>
            {
                var actual = serializer.Deserialize <T>(response);
            });
        }
Ejemplo n.º 35
0
        public void Should_camel_case_field_names_by_default()
        {
            // Given
            var input = new PersonWithFields { FirstName = "Joe", LastName = "Doe" };
            var serializer = new DefaultJsonSerializer(GetTestableEnvironment());

            // When
            var output = new MemoryStream();
            serializer.Serialize("application/json", input, output);
            var actual = Encoding.UTF8.GetString(output.ToArray());

            // Then
            actual.ShouldEqual("{\"firstName\":\"Joe\",\"lastName\":\"Doe\"}");
        }
Ejemplo n.º 36
0
        public void Should_camel_case_property_names_by_default()
        {
            // Given
            var input      = new { FirstName = "Joe", lastName = "Doe" };
            var serializer = new DefaultJsonSerializer(GetTestableEnvironment());

            // When
            var output = new MemoryStream();

            serializer.Serialize("application/json", input, output);
            var actual = Encoding.UTF8.GetString(output.ToArray());

            // Then
            actual.ShouldEqual("{\"firstName\":\"Joe\",\"lastName\":\"Doe\"}");
        }
Ejemplo n.º 37
0
        public void Can_deserialize_all_test_cases()
        {
            var serializer = new DefaultJsonSerializer();
            var files      = Directory.GetFiles("Json", "*.json");

            foreach (var file in files)
            {
                var json     = File.ReadAllText(file);
                var response = new RestResponse <JsonObject>();
                response.SetContent(json);

                var proxy = serializer.DeserializeDynamic(response);
                Assert.IsNotNull(proxy);
            }
        }
        public async Task ConnectViaAppServicesAsync(string packageFamilyName)
        {
            try
            {
                var serializer = new DefaultJsonSerializer(GetType().GetTypeInfo().Assembly);
                var result     = await ASConnection.ConnectLocallyAsync("Chat", packageFamilyName, serializer);

                Client = new RpcClient(result.Connection, this);
                RaisePropertyChanged(nameof(Client));
            }
            catch
            {
                Messages.Add($"Failed to connect to app service in package {packageFamilyName}");
            }
        }
        /// <summary>
        /// Adds a application/json request body to the <see cref="Browser"/>.
        /// </summary>
        /// <param name="browserContext">The <see cref="BrowserContext"/> that the data should be added to.</param>
        /// <param name="model">The model to be serialized to json.</param>
        /// <param name="serializer">Optionally opt in to using a different JSON serializer.</param>
        public static void JsonBody <TModel>(this BrowserContext browserContext, TModel model, ISerializer serializer = null)
        {
            if (serializer == null)
            {
                serializer = new DefaultJsonSerializer(browserContext.Environment);
            }

            var contextValues =
                (IBrowserContextValues)browserContext;

            contextValues.Body = new MemoryStream();

            serializer.Serialize("application/json", model, contextValues.Body);
            browserContext.Header("Content-Type", "application/json");
        }
Ejemplo n.º 40
0
        public void Should_not_change_casing_when_retain_casing_is_true()
        {
            // Given
            var input = new {FirstName = "Joe", lastName = "Doe"};
            var environment = GetTestableEnvironment(x => x.Json(retainCasing: true));
            var serializer = new DefaultJsonSerializer(environment);

            // When
            var output = new MemoryStream();
            serializer.Serialize("application/json", input, output);
            var actual = Encoding.UTF8.GetString(output.ToArray());

            // Then
            actual.ShouldEqual("{\"FirstName\":\"Joe\",\"lastName\":\"Doe\"}");
        }
Ejemplo n.º 41
0
        public void NullValueHandling_Test_Should_Succeed()
        {
            var serializer = new DefaultJsonSerializer("json", new JsonSerializerOptions
            {
                IgnoreNullValues = true
            });

            Employee joe = new Employee {
                Name = "Joe User"
            };

            var joe_byte = serializer.Serialize(joe);
            var joe_obj  = serializer.Deserialize <Employee>(joe_byte);

            Assert.Null(joe.Manager);
        }
Ejemplo n.º 42
0
        public void Should_not_change_casing_when_retain_casing_is_true()
        {
            // Given
            var input       = new { FirstName = "Joe", lastName = "Doe" };
            var environment = GetTestableEnvironment(x => x.Json(retainCasing: true));
            var serializer  = new DefaultJsonSerializer(environment);

            // When
            var output = new MemoryStream();

            serializer.Serialize("application/json", input, output);
            var actual = Encoding.UTF8.GetString(output.ToArray());

            // Then
            actual.ShouldEqual("{\"FirstName\":\"Joe\",\"lastName\":\"Doe\"}");
        }
Ejemplo n.º 43
0
        public void Should_camel_case_dictionary_keys_by_default()
        {
            // Given
            var input = new Dictionary<string, object>
            {
                { "Joe", new PersonWithFields { FirstName = "Joe" } },
                { "John", new PersonWithFields { FirstName = "John" } }
            };

            var serializer = new DefaultJsonSerializer(GetTestableEnvironment());

            // When
            var output = new MemoryStream();
            serializer.Serialize("application/json", input, output);
            var actual = Encoding.UTF8.GetString(output.ToArray());

            // Then
            actual.ShouldEqual("{\"joe\":{\"firstName\":\"Joe\",\"lastName\":null},\"john\":{\"firstName\":\"John\",\"lastName\":null}}");
        }
Ejemplo n.º 44
0
        public void Should_not_change_casing_when_retain_casing_is_true()
        {
            JsonSettings.RetainCasing = true;
            try
            {
                // Given
                var sut = new DefaultJsonSerializer();
                var input = new {FirstName = "Joe", lastName = "Doe"};

                // When
                var output = new MemoryStream();
                sut.Serialize("application/json", input, output);
                var actual = Encoding.UTF8.GetString(output.ToArray());

                // Then
                actual.ShouldEqual("{\"FirstName\":\"Joe\",\"lastName\":\"Doe\"}");
            }
            finally
            {
                JsonSettings.RetainCasing = false;
            }
        }
Ejemplo n.º 45
0
 static GlobalSettings()
 {
     JsonSerializer = new DefaultJsonSerializer();
     RequiredTokenSettings = new RequiredTokenSettings();
 }
Ejemplo n.º 46
0
 public void SerializeCypherRequest__IsValid()
 {
     var request =
         CypherQueryRequest.Create(
                                   @"START x=node(1), y=node(2) CREATE x-[r:OWNS {""name"":""mark""}]->y<-[r2:IS_OWNED_BY {""age"": 33}]");
     var serializer = new DefaultJsonSerializer();
     var result = serializer.Serialize(request);
     Console.WriteLine(result);
 }
Ejemplo n.º 47
0
        public void DerializeJson_EntitiesOnly_ReturnsCollectionOfEntities()
        {
            const string json =
                @"{
               ""commit"":""http://localhost:7474/db/data/transaction/6/commit"",
               ""results"":[
              {
             ""columns"":[
            ""Actor"",
            ""Actor__Id"",
            ""Actor__Labels"",
            ""ActedIn"",
            ""ActedIn__Id"",
            ""ActedIn__Type"",
            ""Movie"",
            ""Movie__Id"",
            ""Movie__Labels""
             ],
             ""data"":[
            [
               {
                  ""age"":33,
                  ""name"":""mark""
               },
               3745,
                [""person""],
               {

               },
               39490,
               ""IS_A"",
               {
                  ""title"":""developer""
               },
               3746,
               []
            ],[
               {
                  ""age"":21,
                  ""name"":""John""
               },
               3747,
               [""person""],
               {

               },
               39491,
               ""IS_A"",
               {
                  ""title"":""leg""
               },
               3748,
               []
            ]
             ]
              }
               ],
               ""transaction"":{
              ""expires"":""Tue, 30 Jul 2013 15:57:59 +0000""
               },
               ""errors"":[

               ]
            }";

            var deserializer = new DefaultJsonSerializer();

            var retval = deserializer.Deserialize<CypherResponse<DeserializationTestClass>>(json);
            Assert.AreEqual(retval.Results.Count(), 2);
            dynamic actor = retval.Results.Select(r => r.Actor).First();
            Assert.AreEqual(actor.age, 33);
            Assert.AreEqual(actor.name, "mark");
        }
Ejemplo n.º 48
0
        public void Should_camel_case_property_names_if_local_override_is_set()
        {
            JsonSettings.RetainCasing = true;
            try
            {
                // Given
                var sut = new DefaultJsonSerializer { RetainCasing = false };
                var input = new { FirstName = "Joe", lastName = "Doe" };

                // When
                var output = new MemoryStream();
                sut.Serialize("application/json", input, output);
                var actual = Encoding.UTF8.GetString(output.ToArray());

                // Then
                actual.ShouldEqual("{\"firstName\":\"Joe\",\"lastName\":\"Doe\"}");
            }
            finally
            {
                JsonSettings.RetainCasing = false;
            }
        }
 public DefaultJsonSerializerTest()
 {
     _serializer = new DefaultJsonSerializer();
 }
Ejemplo n.º 50
0
        public void Should_use_iso8601_datetimes_by_default()
        {
            // Given
            var serializer = new DefaultJsonSerializer(GetTestableEnvironment());
            var input = new
            {
                UnspecifiedDateTime = new DateTime(2014, 3, 9, 17, 03, 25).AddMilliseconds(234),
                LocalDateTime = new DateTime(2014, 3, 9, 17, 03, 25, DateTimeKind.Local).AddMilliseconds(234),
                UtcDateTime = new DateTime(2014, 3, 9, 16, 03, 25, DateTimeKind.Utc).AddMilliseconds(234)
            };

            // When
            var output = new MemoryStream();
            serializer.Serialize("application/json", input, output);
            var actual = Encoding.UTF8.GetString(output.ToArray());

            // Then
            actual.ShouldEqual(string.Format(@"{{""unspecifiedDateTime"":""2014-03-09T17:03:25.2340000{0}"",""localDateTime"":""2014-03-09T17:03:25.2340000{0}"",""utcDateTime"":""2014-03-09T16:03:25.2340000Z""}}",
                GetTimezoneSuffix(input.LocalDateTime, ":")));
        }
Ejemplo n.º 51
0
 public DefaultJsonSerializerFixture()
 {
     this.serializer = new DefaultJsonSerializer();
 }
Ejemplo n.º 52
0
        public void Should_camel_case_property_names_if_local_override_is_set()
        {
            // Given
            var environment = GetTestableEnvironment(x => x.Json(retainCasing: true));
            var serializer = new DefaultJsonSerializer(environment) { RetainCasing = false };

            var input = new { FirstName = "Joe", lastName = "Doe" };

            // When
            var output = new MemoryStream();
            serializer.Serialize("application/json", input, output);
            var actual = Encoding.UTF8.GetString(output.ToArray());

            // Then
            actual.ShouldEqual("{\"firstName\":\"Joe\",\"lastName\":\"Doe\"}");
        }
Ejemplo n.º 53
0
        public void Should_use_wcf_datetimeformat_when_iso8601dateformat_local_override_is_false()
        {
            // Given
            var environment = GetTestableEnvironment(x => x.Json());
            var sut = new DefaultJsonSerializer(environment) { ISO8601DateFormat = false };
            var input = new
            {
                UnspecifiedDateTime = new DateTime(2014, 3, 9, 17, 03, 25).AddMilliseconds(234),
                LocalDateTime = new DateTime(2014, 3, 9, 17, 03, 25, DateTimeKind.Local).AddMilliseconds(234),
                UtcDateTime = new DateTime(2014, 3, 9, 16, 03, 25, DateTimeKind.Utc).AddMilliseconds(234)
            };

            // When
            var output = new MemoryStream();
            sut.Serialize("application/json", input, output);
            var actual = Encoding.UTF8.GetString(output.ToArray());

            // Then
            var ticks = (input.LocalDateTime.ToUniversalTime().Ticks - InitialJavaScriptDateTicks) / (long)10000;
            actual.ShouldEqual(string.Format(@"{{""unspecifiedDateTime"":""\/Date({0}{1})\/"",""localDateTime"":""\/Date({0}{1})\/"",""utcDateTime"":""\/Date(1394381005234)\/""}}",
                ticks, GetTimezoneSuffix(input.LocalDateTime)));
        }