public void Serialize_Deserialize_Test() { var newtonsoftJsonSerializer = new NewtonsoftJsonSerializer(_mockJsonSerializerSettings.Object); Assert.Null(newtonsoftJsonSerializer.Serialize(null)); var o1 = new NewtonsoftJsonSerializerClass1(3) { Id = 1, Name = "HaHa" }; var json1 = newtonsoftJsonSerializer.Serialize(o1); var deserializeO1 = newtonsoftJsonSerializer.Deserialize(json1, typeof(NewtonsoftJsonSerializerClass1)); Assert.Equal(typeof(NewtonsoftJsonSerializerClass1), deserializeO1.GetType()); var jsonSerializer = _provider.GetService <IJsonSerializer>(); var json2 = jsonSerializer.Serialize(o1); Assert.Equal(json1, json2); var deserializeO2 = newtonsoftJsonSerializer.Deserialize <NewtonsoftJsonSerializerClass1>(json1); Assert.Equal(o1.Id, deserializeO2.Id); Assert.Equal(o1.Name, deserializeO2.Name); Assert.Equal(o1.Age, deserializeO2.Age); }
internal ApiOptionalResponse <R> Get <R>(string path, ISearchFilter filter = null) where R : ApiObject { var request = CreateRequest(path, Method.GET, filter); SetTokenAndUri(); #if DEBUG var uri = Client.BuildUri(request); Api.DebugList.Add(uri.ToString()); #endif var response = Client.Execute(request); if (!response.IsSuccessful) { throw new ApiErrorException(response.StatusCode, response.Content); } #if DEBUG Api.DebugResponseList.Add(response); #endif var asRequestResponse = serializerDeserializer.Deserialize <RequestResponse <R> >(response); if ("error" == asRequestResponse.Status) { return(new ApiOptionalResponse <R> { Exception = asRequestResponse.Messages.ContainsKey("general") ? new ApiErrorException(asRequestResponse.Messages["general"]) : new ApiErrorException(asRequestResponse.Messages) }); } return(new ApiOptionalResponse <R> { Value = serializerDeserializer.Deserialize <R>(response) }); }
protected override string DeserializeError(IRestResponse response) { var serializer = new NewtonsoftJsonSerializer(); var deserialized = serializer.Deserialize <EnterpriseErrorWrapper>(response.Content); return(string.Join(",", deserialized.Errors.Select(x => x.Message))); }
public void ConvertFromEntityWithSerializeMapping() { // Arrange var serializer = new NewtonsoftJsonSerializer(); var map = new EntityTypeMap <EntityWithSerializableProperty>(e => e.PartitionKey(x => x.Pk) .RowKey(x => x.Rk) .Serialize(x => x.SerializableEntity, "NestedEntityRaw") ); var entity = new EntityWithSerializableProperty { SerializableEntity = new SerializableEntity { DecimalValue = 4, }, }; // Act var tableEntity = (DynamicTableEntity)map.GetEntity(entity); // Assert Assert.NotNull(tableEntity.Properties["NestedEntityRaw"].StringValue); var deserialized = serializer.Deserialize <SerializableEntity>(tableEntity.Properties["NestedEntityRaw"].StringValue); Assert.Equal(entity.SerializableEntity.DecimalValue, deserialized.DecimalValue); }
public void Deserialize_Should_ConvertBase64StringToByteArray() { const string cardRawJson = "{ \"id\": \"12345\", \"content_snapshot\":\"AQIDBAU=\" }"; var serializer = new NewtonsoftJsonSerializer(); var cardRaw = serializer.Deserialize <RawSignedModel>(cardRawJson); Assert.AreEqual(cardRaw.ContentSnapshot, Bytes.FromString("AQIDBAU=", StringEncoding.BASE64)); }
public async Task <TData> Resolve <TData>(HttpResponse response, IDictionary <string, object> properties) { var content = await response.Content.ReadAsStringAsync(); var _serializer = new NewtonsoftJsonSerializer(); return(_serializer.Deserialize <TData>(content)); }
public static T JsonCopy <T>(T other) { var serializer = new NewtonsoftJsonSerializer(); var serialized = serializer.Serialize(other); var deserialized = serializer.Deserialize <T>(serialized); return(deserialized); }
public void NewtonsoftJsonTest() { var serializer = new NewtonsoftJsonSerializer(); var now = DateTimeOffset.Now; Assert.Equal(now, serializer.Deserialize <DateTimeOffset>(serializer.Serialize(now))); }
public void DeserializeDictionary_Test() { var deserializeStr = "\"Name\":\"gang.yang\",\"Age\":28,\"Time\":\"2016-03-09 14:11:13\""; var json = new NewtonsoftJsonSerializer(); var result = json.Deserialize <Dictionary <string, string> >(deserializeStr); // error Assert.IsNull(result); }
public void DeserializeDictionary_Test() { var deserializeStr = "\"Name\":\"gang.yang\",\"Age\":28,\"Time\":\"2016-03-09 14:11:13\""; var json = new NewtonsoftJsonSerializer(); var result = json.Deserialize<Dictionary<string, string>>(deserializeStr); // error Assert.IsNull(result); }
public void Serialize_Should_ConvertDictionary() { var dict = new Dictionary <string, string>(); dict.Add("username", "anna"); dict.Add("passw", "mypassword"); var serializer = new NewtonsoftJsonSerializer(); var serializedDict = serializer.Serialize(dict); Assert.AreEqual(dict, serializer.Deserialize <Dictionary <string, string> >(serializedDict)); }
public void CustomInstanceAvoidingDateParsin() { string text = "\"2017-05-03T16:38:00Z\""; var settings = NewtonsoftJsonSerializer.CreateDefaultSettings(); settings.DateParseHandling = DateParseHandling.None; var instance = new NewtonsoftJsonSerializer(settings); object value = instance.Deserialize <object>(text); // No magic parsing to DateTime... Assert.IsType <string>(value); }
public void Deserialize() { var serializer = new NewtonsoftJsonSerializer(); const string input = "{\"Age\":35,\"Name\":\"Roger Federer\",\"DateOfBirth\":\"1981-08-08T00:00:00\"}"; var person = serializer.Deserialize <TestPerson>(input); Assert.AreEqual(35, person.Age); Assert.AreEqual(new DateTime(1981, 8, 8), person.DateOfBirth); Assert.AreEqual("Roger Federer", person.Name); }
protected override async Task <IEnumerable <byte> > HandleCall(HttpListenerRequest request, HttpListenerResponse response) { var ret = await base.HandleCall(request, response); var serializer = new NewtonsoftJsonSerializer(); if (Requests.Count == 1) { Request = serializer.Deserialize <TRequest>(request.InputStream); } var responseBody = new MemoryStream(); serializer.Serialize(_expectedResponse, responseBody); return(responseBody.ToArray()); }
public void CanUsePrivateSetterInFullTrustEnvironment() { Byte[] json = Encoding.UTF8.GetBytes("{\"$type\":\"Test.Spark.Serialization.UsingNewtonsoftJsonSerializer.WhenDeserializingData+ClassWithPrivateSetter, Spark.Serialization.Newtonsoft.Tests\",\"t\":\"Test String\"}"); NewtonsoftJsonSerializer serializer = new NewtonsoftJsonSerializer(new DataMemberContractResolver(Enumerable.Empty <JsonConverter>())); ClassWithPrivateSetter graph; using (var memoryStream = new MemoryStream(json, writable: false)) { serializer.Serializer.Formatting = Formatting.None; graph = (ClassWithPrivateSetter)serializer.Deserialize(memoryStream, typeof(Object)); } Assert.Equal("Test String", graph.Test); }
public void UseDefaultConstructorWhenSpecified() { Byte[] json = Encoding.UTF8.GetBytes("{\"$type\":\"Test.Spark.Serialization.UsingNewtonsoftJsonSerializer.WhenDeserializingData+ClassWithDefaultConstructor, Spark.Serialization.Newtonsoft.Tests\",\"test\":\"Test String\"}"); NewtonsoftJsonSerializer serializer = new NewtonsoftJsonSerializer(new DataMemberContractResolver(Enumerable.Empty <JsonConverter>())); ClassWithDefaultConstructor graph; using (var memoryStream = new MemoryStream(json, writable: false)) { serializer.Serializer.Formatting = Formatting.None; graph = (ClassWithDefaultConstructor)serializer.Deserialize(memoryStream, typeof(Object)); } Assert.Equal("Test String", graph.Test); Assert.True(graph.DefaultConstructorInvoked); }
public void Deserialize_Should_EquivalentToOrigin() { var rawCard = faker.PredefinedRawSignedModel(null, true); var serializer = new NewtonsoftJsonSerializer(); var serializedRawCard = serializer.Serialize(rawCard); var deserializeRawCard = serializer.Deserialize <RawSignedModel>(serializedRawCard); Assert.IsTrue(deserializeRawCard.ContentSnapshot.SequenceEqual(rawCard.ContentSnapshot)); var first = deserializeRawCard.Signatures.First(); var sec = rawCard.Signatures.First(); Assert.AreEqual(first.Signature, sec.Signature); Assert.AreEqual(first.Snapshot, sec.Snapshot); Assert.IsTrue(deserializeRawCard.ContentSnapshot.SequenceEqual(rawCard.ContentSnapshot)); }
public void TestDeSerializeJsonNet() { var jsonSerializer = new NewtonsoftJsonSerializer(); var r = jsonSerializer.Serialize(new ValueObject { A = 10, B = 20, }); Assert.AreNotEqual(r, null); var s = jsonSerializer.Deserialize <ValueObject>(r); Assert.AreEqual(s.A, 10); }
public void DeserializationShouldWorkCorrectly() { // Arrange. var filter = new GzipCompressionMessageFilter(); var envelope = Envelope.Create(new CreateOrderCommand { Id = "abc" }) .Property("Something", 123); var serializer = new NewtonsoftJsonSerializer(); var serializedBody = serializer.Serialize(envelope.Body).Result; var compressedBody = filter.AfterSerialization(envelope, serializedBody).Result; // Act. var decompressedBody = filter.BeforeDeserialization(envelope, compressedBody).Result; var command = serializer.Deserialize<CreateOrderCommand>(decompressedBody).Result; // Assert. Assert.Equal(envelope.Body.Id, command.Id); }
public void MessagePack_SerializeAndDeSerialize_ReturnSame() { // arrange var sut = new NewtonsoftJsonSerializer(); var actual = new RefTypeObject { foo = 1, bar = "test", Created = DateTime.UtcNow }; // act var bytes = sut.Serialize(actual); var expected = sut.Deserialize <RefTypeObject>(bytes); // assert Assert.Equal(expected, actual); }
public void DeserializationShouldWorkCorrectly() { // Arrange. var filter = new GzipCompressionMessageFilter(); var envelope = Envelope.Create(new CreateOrderCommand { Id = "abc" }) .Property("Something", 123); var serializer = new NewtonsoftJsonSerializer(); var serializedBody = serializer.Serialize(envelope.Body).Result; var compressedBody = filter.AfterSerialization(envelope, serializedBody).Result; // Act. var decompressedBody = filter.BeforeDeserialization(envelope, compressedBody).Result; var command = serializer.Deserialize <CreateOrderCommand>(decompressedBody).Result; // Assert. Assert.Equal(envelope.Body.Id, command.Id); }
public Task <IRestResponse <T> > ExecuteAsync <T>(IRestRequest request) { var result = new Mock <IRestResponse <T> >(); var b = request.Body; var o = (Doods.Openmediavault.Rpc.Std.RpcRequest)request.Parameters[0].Value; var s = request.JsonSerializer; var toto = Directory.GetCurrentDirectory(); var path = @$ "{toto}/Data/{OmvV}/Error.json"; if (o.Method == "getOutput") { System.Type type = o.Params.GetType(); string filename = (string)type.GetProperty("filename").GetValue(o.Params, null); if (!string.IsNullOrWhiteSpace(filename)) { path = @$ "{toto}/Data/{OmvV}/{filename}.json"; } } else { path = @$ "{toto}/Data/{OmvV}/{o.Service}_{o.Method}.json"; } //if (!File.Exists(path)) //{ // path = @$"{toto}/Data/V6/Error.json"; //} string jsonString = File.ReadAllText(path); result.Setup(c => c.Data).Returns(() => { var obj = _serializer.Deserialize <T>(jsonString); return(obj); }); return(Task.FromResult(result.Object)); }
static AuthenticationService() { NewtonsoftJsonSerializer njs = new NewtonsoftJsonSerializer(); var config = njs.Deserialize <Config>(File.ReadAllText(@"appsettings.json")); var apiKeyBase64 = config.API_KEY; var privateKeyData = Bytes.FromString(apiKeyBase64, StringEncoding.BASE64); var crypto = new VirgilCrypto(); var apiKey = crypto.ImportPrivateKey(privateKeyData); var accessTokenSigner = new VirgilAccessTokenSigner(); var appId = config.APP_ID; var apiKeyId = config.API_KEY_ID; var ttl = TimeSpan.FromHours(1); // 1 hour (JWT's lifetime) _jwtGenerator = new JwtGenerator(appId, apiKey, apiKeyId, ttl, accessTokenSigner); _authTokens = new Dictionary <string, string>(); }
public Task <IRestResponse <T> > ExecuteAsync <T>(IRestRequest request) { var result = new Mock <IRestResponse <T> >(); var b = request.Body; var o = (string)request.Parameters[0].Value; var oo = (string)request.Parameters[2].Value; var s = request.JsonSerializer; var toto = Directory.GetCurrentDirectory(); var path = @$ "{toto}/Data/Json/{o}.{oo}.json"; if (!string.IsNullOrWhiteSpace(ExtendJsonFileName)) { if (ExtendJsonFileName.Contains(@$ "{o}.{oo}")) { path = @$ "{toto}/Data/Json/{ExtendJsonFileName}.json"; } } //if (!File.Exists(path)) //{ // path = @$"{toto}/Data/V6/Error.json"; //} string jsonString = File.ReadAllText(path); result.Setup(c => c.Data).Returns(() => { var obj = _serializer.Deserialize <T>(jsonString); return(obj); }); return(Task.FromResult(result.Object)); }
public void CanUsePrivateSetterInFullTrustEnvironment() { Byte[] json = Encoding.UTF8.GetBytes("{\"$type\":\"Test.Spark.Serialization.UsingNewtonsoftJsonSerializer.WhenDeserializingData+ClassWithPrivateSetter, Spark.Serialization.Newtonsoft.Tests\",\"t\":\"Test String\"}"); NewtonsoftJsonSerializer serializer = new NewtonsoftJsonSerializer(new DataMemberContractResolver(Enumerable.Empty<JsonConverter>())); ClassWithPrivateSetter graph; using (var memoryStream = new MemoryStream(json, writable: false)) { serializer.Serializer.Formatting = Formatting.None; graph = (ClassWithPrivateSetter)serializer.Deserialize(memoryStream, typeof(Object)); } Assert.Equal("Test String", graph.Test); }
//[TestMethod] //public async Task GetPackagesServerInfoJson() //{ // var client = new Mock<ISynoWebApi>(); // var toto = Directory.GetCurrentDirectory(); // client.Setup(c => c.ExecuteAsync<SynologyResponse<SynologyPackageInfo>>(It.IsAny<IRestRequest>())) // .ReturnsAsync(new RestResponse<SynologyResponse<SynologyPackageInfo>>() // { // Data = GetResult<SynologyResponse<SynologyPackageInfo>>(@$"{toto}/Data/Json/SYNO.Core.Package_list.json") // }); // var c = new SynoPackageClient(client.Object); // var result = await c.GetPackagesInfo(); // Assert.IsNotNull(result); //} private T GetResult <T>(string jsonFile) { var serialiser = new NewtonsoftJsonSerializer(); return(serialiser.Deserialize <T>(File.ReadAllText(jsonFile))); }
public static ResponseProjectModel GetResponseProjectModel(this HttpResponseMessage responseMessage) { return(NewtonsoftJsonSerializer.Deserialize <ResponseProjectModel>(responseMessage)); }
public void Deserialize() { Item = _serializer.Deserialize <T>(Json); }
public static T Deserialize <T>(string value) where T : class { return(_jsonSerializer.Deserialize <T>(value)); }
public static Error GetErrors(this HttpResponseMessage responseMessage) { return(NewtonsoftJsonSerializer.Deserialize <Error>(responseMessage)); }
public static T Deserialize <T>(string content) { return(_serializer.Deserialize <T>(content)); }
public void UseDefaultConstructorWhenSpecified() { Byte[] json = Encoding.UTF8.GetBytes("{\"$type\":\"Test.Spark.Serialization.UsingNewtonsoftJsonSerializer.WhenDeserializingData+ClassWithDefaultConstructor, Spark.Serialization.Newtonsoft.Tests\",\"test\":\"Test String\"}"); NewtonsoftJsonSerializer serializer = new NewtonsoftJsonSerializer(new DataMemberContractResolver(Enumerable.Empty<JsonConverter>())); ClassWithDefaultConstructor graph; using (var memoryStream = new MemoryStream(json, writable: false)) { serializer.Serializer.Formatting = Formatting.None; graph = (ClassWithDefaultConstructor)serializer.Deserialize(memoryStream, typeof(Object)); } Assert.Equal("Test String", graph.Test); Assert.True(graph.DefaultConstructorInvoked); }