public void VerifyDictionaryConverter() { var dic = new Dictionary <string, object> { { "Field1", "Value1" }, { "Field2", "Value2" }, { "NestedObject", new Dictionary <string, object> { { "NestedField", 1 } } } }; var expected = @"{""Field1"":""Value1"",""Field2"":""Value2"",""NestedObject"":{""NestedField"":1}}"; { var dicString = JsonSerializer.Serialize(dic, _jsonSerializerOptions); Assert.NotEmpty(dicString); Assert.Equal(expected, dicString); } { var dicString = JsonConvert.SerializeObject(dic); Assert.NotEmpty(dicString); Assert.Equal(expected, dicString); } }
public ActionResult <string> AvaliacoesAgendadas([FromBody] dynamic rec) { lock (_system) { var jobject = JObject.Parse(JsonSerializer.Serialize(rec)); if (!_system.isUserOnline(jobject.valueST.ToString())) { return(Unauthorized("Client Offline")); } string email = jobject.email.ToString(); List <Avaliaçao> av = _system.GetAvaAgendCli(email); JArray array = new JArray(); foreach (Avaliaçao a in av) { JObject tmp = new JObject(); tmp.Add("instrutor_email", a.instrutor_email); tmp.Add("instrutor_nome", _system.GetUser(a.instrutor_email).GetName()); tmp.Add("data", a.data.ToString("yyyy-MM-dd HH:mm:ss")); array.Add(tmp); } JObject avaliacoes = new JObject(); avaliacoes.Add("avaliacoes", array); return(Ok(avaliacoes.ToString())); } }
public XPaginationHeader( IPaginationMetadata pagination, Func <object, string> urlBuilder, CollectionConfig collectionConfig) { _collectionConfig = collectionConfig; var metadata = new { totalCount = pagination.TotalCount, pageSize = pagination.PageSize, currentPage = pagination.CurrentPage, totalPages = pagination.TotalPages, previousPageUrl = pagination.HasPrevious ? CreatePlayersResourceUri(ResourceUriType.PreviousPage, urlBuilder) : null, nextPageUrl = pagination.HasNext ? CreatePlayersResourceUri(ResourceUriType.NextPage, urlBuilder) : null }; var key = "X-Pagination"; var value = JsonSerializer.Serialize(metadata, new JsonSerializerOptions() { // NOTE: Stops the '?' & '&' chars in the links being escaped Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, IgnoreNullValues = true }); Value = new KeyValuePair <string, StringValues>(key, value); }
public async Task <Response> RegisterUserAsync(RegisterModel model) { Uri uri = new Uri(string.Format(Constants.RegisterUrl, string.Empty)); try { string json = JsonSerializer.Serialize <RegisterModel>(model, serializerOptions); StringContent content = new StringContent(json, Encoding.UTF8, "application/json"); HttpResponseMessage response = null; response = await client.PostAsync(uri, content); string jsonresponse = await response.Content.ReadAsStringAsync(); Response response2 = JsonSerializer.Deserialize <Response>(jsonresponse, serializerOptions); if (response.IsSuccessStatusCode) { Debug.WriteLine(@"\user successfully created."); } return(response2); } catch (Exception ex) { Debug.WriteLine(@"\tERROR {0}", ex.Message); return(new Response() { Status = Constants.Status.Error, Message = Constants.APIMessages.ErrorOnRegisterFailed }); } }
string GetObjectInfo(object obj, string title) { if (obj == null) { return(string.Empty); } var strBuilder = new StringBuilder(); strBuilder.AppendLine(title); strBuilder.AppendLine($"Type -> {obj.GetType().Name}"); Type objType = obj.GetType(); var resultProp = objType.GetProperties() .FirstOrDefault(x => x.Name.Equals(nameof(FlowResult.Result))); var result = resultProp?.GetValue(obj); if (result != null) { var serialized = JsonSerializer.Serialize(obj, options: new JsonSerializerOptions() { PropertyNameCaseInsensitive = true, IgnoreNullValues = true, }); strBuilder.AppendLine("Object result props:"); strBuilder.AppendLine(serialized); } return(strBuilder.ToString()); }
public async Task <string> GetLocationsAsync(ClaimsPrincipal user) { int userid; if (!int.TryParse(user.Claims.FirstOrDefault(x => x.Type == "ID").Value, out userid)) { return(null); } var User = await _context.Users .Include(x => x.UserLocations) .ThenInclude(y => y.Location) .FirstOrDefaultAsync(x => x.UserID == userid); if (User != null) { var LocationNames = User.UserLocations.Select(x => new { ID = x.Location.ID, Name = x.Location.Name }).ToList(); var jsonLocations = JsonSerializer.Serialize(LocationNames); return(jsonLocations); } return(null); }
public async Task <Response> UpdateUserAsync(UpdateUserModel model) { Uri uri = new Uri(string.Format(Constants.UpdateUserProfileUrl, string.Empty)); try { string json = JsonSerializer.Serialize <UpdateUserModel>(model, serializerOptions); StringContent content = new StringContent(json, Encoding.UTF8, "application/json"); client.DefaultRequestHeaders.Add("Authorization", $"Bearer {this.BearerToken}"); HttpResponseMessage response = null; response = await client.PatchAsync(uri, content); string jsonresponse = await response.Content.ReadAsStringAsync(); Response response2 = JsonSerializer.Deserialize <Response>(jsonresponse, serializerOptions); if (response.IsSuccessStatusCode) { Debug.WriteLine(@"\user password successfully saved."); } return(response2); } catch (Exception ex) { Debug.WriteLine(@"\tERROR {0}", ex.Message); return(new Response() { Status = Constants.Status.Error, Message = Constants.APIMessages.ErrorOnUpdate }); } }
public async Task <string> Get(Login loginData) { var idsHospitalization = new List <object>(); var request = new QueryRequest { TableName = tableName, KeyConditions = new Dictionary <string, Condition> { { primaryPartitionKey, new Condition() { ComparisonOperator = ComparisonOperator.EQ, AttributeValueList = new List <AttributeValue> { new AttributeValue { S = JsonSerializer.Serialize(loginData) } } } } } }; var result = await amazonDynamoDbClient.QueryAsync(request); foreach (var item in result.Items) { var document = Document.FromAttributeMap(item); idsHospitalization.Add(document[idHospitalizationIndex].ToString()); } var guidId = (idsHospitalization.FirstOrDefault() ?? string.Empty).ToString(); return(guidId); }
/// <summary> /// (Serialize)JSON 序列化 /// </summary> /// <param name="implType"></param> /// <param name="value"></param> /// <param name="inputType"></param> /// <param name="writeIndented"></param> /// <param name="ignoreNullValues"></param> /// <returns></returns> public static string SJSON(JsonImplType implType, object?value, Type?inputType = null, bool writeIndented = false, bool ignoreNullValues = false) { switch (implType) { case JsonImplType.SystemTextJson: var options = new SJsonSerializerOptions { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, WriteIndented = writeIndented, //IgnoreNullValues = ignoreNullValues }; if (ignoreNullValues) { options.DefaultIgnoreCondition = SJsonIgnoreCondition.WhenWritingNull; } return(SJsonSerializer.Serialize(value, inputType ?? value?.GetType() ?? typeof(object), options)); default: #if NOT_NJSON throw new NotSupportedException(); #else var formatting = writeIndented ? Formatting.Indented : Formatting.None; var settings = ignoreNullValues ? new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore } : null; return(SerializeObject(value, inputType, formatting, settings)); #endif } }
public async Task <bool> UpdateProfil(UserUpdate userUpdate, string token) { Uri uri = new Uri(Constant.URL_UPDATE_PROFIL); try { string json = JsonSerializer.Serialize <UserUpdate>(userUpdate); StringContent content = new StringContent(json, Encoding.UTF8, "application/json"); HttpResponseMessage response = null; client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); var method = new HttpMethod("PATCH"); var request = new HttpRequestMessage(method, uri) { Content = new StringContent( JsonConvert.SerializeObject(userUpdate), Encoding.UTF8, "application/json") }; response = await client.SendAsync(request); string contentResponse = await response.Content.ReadAsStringAsync(); GetUser code = JsonConvert.DeserializeObject <GetUser>(contentResponse); return(code.is_success); } catch (Exception ex) { return(false); } }
public async Task InvokeAsync(HttpContext context) { try { await _next(context); } catch (Exception e) { _logger.LogError(e, e.Message); context.Response.ContentType = "application/json"; context.Response.StatusCode = 500; var response = new ProblemDetails { Status = 500, Detail = _env.IsDevelopment() ? e.StackTrace?.ToString() : null, Title = e.Message }; var options = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }; var json = JsonSerializer.Serialize(response, options); await context.Response.WriteAsync(json); } }
public async Task <bool> Inscription(UserRegister user) { Uri uri = new Uri(Constant.URL_USER_INSCRIPTION); try { string json = JsonSerializer.Serialize <UserRegister>(user); StringContent content = new StringContent(json, Encoding.UTF8, "application/json"); HttpResponseMessage response = null; response = await client.PostAsync(uri, content); string contentResponse = await response.Content.ReadAsStringAsync(); GetLoginData code = JsonConvert.DeserializeObject <GetLoginData>(contentResponse); return(code.is_success); } catch (Exception ex) { return(false); } return(false); }
public async Task <GetLoginData> RefreshToken(string token) { RefreshToken refreshToken = new RefreshToken(token); Uri uri = new Uri(Constant.URL_REFRESH_TOKEN); GetLoginData loginData = null; try { string json = JsonSerializer.Serialize <RefreshToken>(refreshToken); StringContent content = new StringContent(json, Encoding.UTF8, "application/json"); HttpResponseMessage response = null; response = await client.PostAsync(uri, content); string contentResponse = await response.Content.ReadAsStringAsync(); if (response.IsSuccessStatusCode) { loginData = JsonConvert.DeserializeObject <GetLoginData>(contentResponse); Debug.WriteLine(@"\tTodoItem successfully saved."); } else { return(null); } } catch (Exception ex) { } return(loginData); }
public void MergeOptions() { var json1 = JsonSerializer.Serialize(new A { Field1 = "Value1", Field2 = "Value2", NestedObject = new A.B { NestedField = 1 } }); var json2 = JsonSerializer.Serialize(new A { NestedObject = new A.B { NestedField = 100 } }); var mergedJson = JsonExtensions.Merge(json1, json2); var finalJson = JsonSerializer.Deserialize <A>(mergedJson); Assert.NotNull(mergedJson); Assert.NotEmpty(mergedJson); Assert.Equal(100, finalJson.NestedObject?.NestedField); }
public async Task Update(Category category) { var categoryJson = new StringContent(JsonSerializer.Serialize(category), Encoding.UTF8, "application/json"); await _httpClient.PutAsync("api/category", categoryJson); }
public async Task ThenItShouldSerializeReturnSerializedObjectIfValidForSchema(BasicObject data) { var schemaRegistryClientMock = GetSchemaRegistryClientMock(); schemaRegistryClientMock.Setup(c => c.ListSchemaVersionsAsync(It.IsAny <string>(), It.IsAny <CancellationToken>())) .ReturnsAsync(new[] { 1, 2, 3 }); schemaRegistryClientMock.Setup(c => c.GetSchemaAsync(It.IsAny <string>(), It.IsAny <int>(), It.IsAny <CancellationToken>())) .ReturnsAsync(new SchemaDetails { Id = 123, Version = 3, SchemaType = "JSON", Subject = "some-test-subject", Schema = DefaultBasicObjectSchemaJson, }); var serializer = new KafkaJsonSerializer <BasicObject>(schemaRegistryClientMock.Object, DefaultJsonSerializerOptions); var actual = await serializer.SerializeAsync(data, GetContext()); var expected = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(data, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase })); Assert.AreEqual(expected, actual); }
public async Task <string?> GetOrRefreshTokenAsync() { if (_lastUpdateToken.AddMinutes(25) >= SystemTime.Now()) { return(_token); } using var client = _httpClientFactory.CreateClient(); client.BaseAddress = new Uri(_channel.MasterCommunication !.ToString()); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", _token); using var content = new StringContent(JsonSerializer.Serialize(_channel), Encoding.Default, "application/json"); var message = client.PutAsync(new Uri($"{client.BaseAddress}api/channel"), content); var result = JsonSerializer.Deserialize <ConnectionInfo>(await(await message.ConfigureAwait(false)).Content.ReadAsStringAsync().ConfigureAwait(false), new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }); _token = result?.Token; _lastUpdateToken = SystemTime.Now(); _logger.Information(LogLanguage.Instance.GetMessageFromKey(LogLanguageKey.SECURITY_TOKEN_UPDATED)); return(_token); }
protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var tiempo = Stopwatch.StartNew(); _logger.LogInformation("Inicia el Request"); var response = await base.SendAsync(request, cancellationToken); if (response.IsSuccessStatusCode) { var contenido = await response.Content.ReadAsStringAsync(); var options = new JsonSerializerOptions { PropertyNameCaseInsensitive = true }; var resultado = JsonSerializer.Deserialize <LibroModeloRemoto>(contenido, options); if (resultado.AutorLibro != null) { var responseAutor = await _autorRemote.GetAutor(resultado.AutorLibro ?? Guid.Empty); if (responseAutor.resultado) { var objetoAutor = responseAutor.autor; resultado.AutorData = objetoAutor; var resultadoStr = JsonSerializer.Serialize(resultado); response.Content = new StringContent(resultadoStr, System.Text.Encoding.UTF8, "application/json"); } } } _logger.LogInformation($"El proceso se hizo en {tiempo.ElapsedMilliseconds}ms"); return(response); }
public static void Attaching_a_serialized_graph_4() { Console.WriteLine($">>>> Sample: {nameof(Attaching_a_serialized_graph_4)}"); Console.WriteLine(); Helpers.RecreateCleanDatabase(); Helpers.PopulateDatabase(); using var context = new BlogsContext(); var posts = context.Posts.Include(e => e.Blog).ToList(); #region Attaching_a_serialized_graph_4 var serialized = JsonSerializer.Serialize( posts, new JsonSerializerOptions { ReferenceHandler = ReferenceHandler.Preserve, WriteIndented = true }); #endregion Console.WriteLine(serialized); UpdatePostsFromJson(serialized); }
public async Task <User> ValidateUserLogin(string username, string password) { HttpClient client = new HttpClient(); User user = new() { Username = username, Password = password }; string userAsJson = JsonSerializer.Serialize(user); StringContent content = new StringContent( userAsJson, Encoding.UTF8, "application/json" ); HttpResponseMessage responseMessage = await client.PostAsync("https://localhost:5004/User", content); if (!responseMessage.IsSuccessStatusCode) { throw new Exception($"Error: {responseMessage.StatusCode}, {responseMessage.ReasonPhrase}"); } string someUser = await responseMessage.Content.ReadAsStringAsync(); User finalUser = JsonSerializer.Deserialize <User>(someUser, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }); return(finalUser); } }
public async Task <Response> DeleteUserAsync(string id) { Uri uri = new Uri(string.Format(Constants.DeleteUserUrl)); DeleteUserModel userModel = new DeleteUserModel { UserId = id }; try { string json = JsonSerializer.Serialize <DeleteUserModel>(userModel, serializerOptions); var content = new StringContent(json, Encoding.UTF8, "application/json"); client.DefaultRequestHeaders.Add("Authorization", $"Bearer {this.BearerToken}"); HttpResponseMessage response = await client.PostAsync(uri, content); string jsonresponse = await response.Content.ReadAsStringAsync(); Response response2 = JsonSerializer.Deserialize <Response>(jsonresponse, serializerOptions); if (response.IsSuccessStatusCode) { Debug.WriteLine(@"\user successfully deleted."); } return(response2); } catch (Exception ex) { Debug.WriteLine(@"\tERROR {0}", ex.Message); return(new Response() { Status = Constants.Status.Error, Message = Constants.APIMessages.ErrorOnDeletion }); } }
public async Task Update(Product product) { var productJson = new StringContent(JsonSerializer.Serialize(product), Encoding.UTF8, "application/json"); await _httpClient.PutAsync("api/product", productJson); }
public async Task SaveUserAsync(ApplicationUser user, bool isNewUser) { Uri uri = new Uri(string.Format(Constants.GetUserUrl, string.Empty)); try { string json = JsonSerializer.Serialize <ApplicationUser>(user, serializerOptions); StringContent content = new StringContent(json, Encoding.UTF8, "application/json"); client.DefaultRequestHeaders.Add("Authorization", $"Bearer {this.BearerToken}"); HttpResponseMessage response = null; if (isNewUser) { response = await client.PostAsync(uri, content); } else { response = await client.PutAsync(uri, content); } if (response.IsSuccessStatusCode) { Debug.WriteLine(@"\user successfully saved."); } } catch (Exception ex) { Debug.WriteLine(@"\tERROR {0}", ex.Message); } }
public override void Write(Utf8JsonWriter writer, PluginData value, JsonSerializerOptions options) { writer.WriteStartObject(); if (value.Data == null) { writer.WriteNull("Data"); } else { writer.WriteStartObject("Data"); foreach (KeyValuePair <string, Tuple <Type, object> > keyValuePair in value.Data) { writer.WriteStartObject(keyValuePair.Key); writer.WriteString("Item1", keyValuePair.Value.Item1.FullName); writer.WritePropertyName("Item2"); JsonSerializer.Serialize(writer, keyValuePair.Value.Item2); writer.WriteEndObject(); } writer.WriteEndObject(); } writer.WriteEndObject(); }
public async Task SetTransforms(TransformCollection transforms) { using (var writer = File.CreateText(PATH)) { var json = JsonSerializer.Serialize(transforms); await writer.WriteLineAsync(json); } }
public async Task <ActionResult <IEnumerable <CompanyDto> > > GetCompanies([FromQuery] CompanyDtoParameter parameters) { var companies = await _companyRepository.GetCompaniesAsync(parameters); var previousPageLink = companies.HasPrevious ? CreateCompaniesResourceUri(parameters, ResourceUriType.PreviousPage) : null; var nextPageLink = companies.HasNext ? CreateCompaniesResourceUri(parameters, ResourceUriType.NextPage) : null; var paginationMetadata = new { totalCount = companies.TotalCount, totalPages = companies.TotalPages, currentPage = companies.CurrentPage, pageSize = companies.PageSize, previousPageLink, nextPageLink }; Response.Headers.Add("X-Pagination", JsonSerializer.Serialize(paginationMetadata, new JsonSerializerOptions { Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping })); var companyDtos = _mapper.Map <IEnumerable <CompanyDto> >(companies); return(Ok(companyDtos)); }
public ActionResult <string> UltimaAvaliacao([FromBody] dynamic rec) { lock (_system) { var jobject = JObject.Parse(JsonSerializer.Serialize(rec)); if (!_system.isUserOnline(jobject.valueST.ToString())) { return(Unauthorized("Client Offline")); } string email = jobject.email.ToString(); Avaliaçao av = _system.GetUltAvaliaçaoR(email); if (av == null) { return(NotFound("Utilizador ainda não tem Avaliaçoes")); } JObject job = JObject.Parse(JsonConvert.SerializeObject(av)); var nome = _system.GetUser(email).GetName(); //---------------- Patch job.Remove("id"); job.Remove("realizada"); job.Remove("instrutor_email"); job.Add("comentario", " "); job.Add("massa_gorda_img", " "); job.Add("cliente_nome", nome); //------------ return(Ok(job.ToString())); } }
public async Task <CategoryModel> Add(Category category) { var categoryJson = new StringContent(JsonSerializer.Serialize(category), Encoding.UTF8, "application/json"); using var response = await _httpClient.PostAsync("api/category", categoryJson); var content = await response.Content.ReadAsStringAsync(); if (response.IsSuccessStatusCode) { return(JsonConvert.DeserializeObject <CategoryModel>(content)); } var errorKeyPair = JsonConvert.DeserializeObject <Dictionary <string, string[]> >(content); var errors = errorKeyPair.Select( item => new ApiError { FieldName = item.Key, Description = item.Value.ToList().FirstOrDefault() }).ToList(); return(new CategoryModel { Errors = errors }); }
public async Task InvokeAsync(HttpContext context) { try { await _next(context); } catch (Exception ex) { _logger.LogError(ex, ex.Message); context.Response.ContentType = "application/json"; context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; var response = _env.IsDevelopment() ? new ApiException(context.Response.StatusCode, ex.Message, ex.StackTrace?.ToString()) : new ApiException(context.Response.StatusCode, "Internal Server Error"); var options = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }; var json = JsonSerializer.Serialize(response, options); await context.Response.WriteAsync(json); ; } }
public async Task <List <School> > GetSchoolList() { string cachedSchoolsDetail = await _redisCache.GetStringAsync("schools"); if (cachedSchoolsDetail == null || string.IsNullOrEmpty(cachedSchoolsDetail)) { var schoolList = await schoolUnitOfWork.Repository.GetAll(); cachedSchoolsDetail = JsonSerializer.Serialize <List <School> >(schoolList.ToList()); var options = new DistributedCacheEntryOptions(); options.SetAbsoluteExpiration(DateTimeOffset.Now.AddMinutes(1)); await _redisCache.SetStringAsync("schools", cachedSchoolsDetail); } JsonSerializerOptions opt = new JsonSerializerOptions() { PropertyNameCaseInsensitive = true }; var schoolListCol = JsonSerializer.Deserialize <List <School> >(cachedSchoolsDetail, opt); return(schoolListCol.ToList()); //var schoolList = await schoolUnitOfWork.Repository.GetAll(); //return schoolList.ToList(); //return schoolList.Select(s => new SchoolDetailsDto //{ // SchoolId = s.SchoolId, // SchoolName = s.SchoolName, // Country = s.Country, // CommunicationLanguage = s.CommunicationLanguage, // User = s.User, // Program = s.Program, // AssessmentPeriod = s.AssessmentPeriod //}).ToList(); }