Migrates from Newtonsoft.Json to System.Text.Json (#1658)

* Included System.Text.Json related changes

* Fixed order details summary in WebMVC

* Updated custom JsonConverter
This commit is contained in:
Sumit Ghosh 2021-05-03 16:36:31 +05:30 коммит произвёл GitHub
Родитель c4d40f16db
Коммит 19baeb7069
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 4AEE18F83AFDEB23
40 изменённых файлов: 206 добавлений и 133 удалений

Просмотреть файл

@ -24,7 +24,6 @@
<PackageReference Include="Grpc.Tools" Version="2.34.0" PrivateAssets="All" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="5.0.2" />
<PackageReference Include="Microsoft.AspNetCore.Diagnostics.HealthChecks" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="5.0.2" />
<PackageReference Include="Microsoft.Extensions.Diagnostics.HealthChecks" Version="5.0.2" />
<PackageReference Include="Serilog.AspNetCore" Version="3.4.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="4.0.0-dev-00834" />

Просмотреть файл

@ -2,9 +2,9 @@
using Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Models;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using System.Net.Http;
using System.Threading.Tasks;
using System.Text.Json;
namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Services
{
@ -24,14 +24,17 @@ namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator.Services
public async Task<OrderData> GetOrderDraftFromBasketAsync(BasketData basket)
{
var uri = _urls.Orders + UrlsConfig.OrdersOperations.GetOrderDraft();
var content = new StringContent(JsonConvert.SerializeObject(basket), System.Text.Encoding.UTF8, "application/json");
var content = new StringContent(JsonSerializer.Serialize(basket), System.Text.Encoding.UTF8, "application/json");
var response = await _apiClient.PostAsync(uri, content);
response.EnsureSuccessStatusCode();
var ordersDraftResponse = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<OrderData>(ordersDraftResponse);
return JsonSerializer.Deserialize<OrderData>(ordersDraftResponse, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
}
}
}

Просмотреть файл

@ -107,7 +107,7 @@ namespace Microsoft.eShopOnContainers.Mobile.Shopping.HttpAggregator
services.Configure<UrlsConfig>(configuration.GetSection("urls"));
services.AddControllers()
.AddNewtonsoftJson();
.AddJsonOptions(options => options.JsonSerializerOptions.WriteIndented = true);
services.AddSwaggerGen(options =>
{

Просмотреть файл

@ -2,9 +2,9 @@
using Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Models;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using System.Net.Http;
using System.Threading.Tasks;
using System.Text.Json;
namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Services
{
@ -24,14 +24,17 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator.Services
public async Task<OrderData> GetOrderDraftFromBasketAsync(BasketData basket)
{
var url = _urls.Orders + UrlsConfig.OrdersOperations.GetOrderDraft();
var content = new StringContent(JsonConvert.SerializeObject(basket), System.Text.Encoding.UTF8, "application/json");
var content = new StringContent(JsonSerializer.Serialize(basket), System.Text.Encoding.UTF8, "application/json");
var response = await _apiClient.PostAsync(url, content);
response.EnsureSuccessStatusCode();
var ordersDraftResponse = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<OrderData>(ordersDraftResponse);
return JsonSerializer.Deserialize<OrderData>(ordersDraftResponse, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
}
}
}

Просмотреть файл

@ -130,7 +130,7 @@ namespace Microsoft.eShopOnContainers.Web.Shopping.HttpAggregator
services.Configure<UrlsConfig>(configuration.GetSection("urls"));
services.AddControllers()
.AddNewtonsoftJson();
.AddJsonOptions(options => options.JsonSerializerOptions.WriteIndented = true);
services.AddSwaggerGen(options =>
{

Просмотреть файл

@ -25,7 +25,6 @@
<PackageReference Include="Grpc.Tools" Version="2.34.0" PrivateAssets="All" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="5.0.2" />
<PackageReference Include="Microsoft.AspNetCore.Diagnostics.HealthChecks" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="5.0.2" />
<PackageReference Include="Microsoft.Extensions.Diagnostics.HealthChecks" Version="5.0.2" />
<PackageReference Include="Serilog.AspNetCore" Version="3.4.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="4.0.0-dev-00834" />

Просмотреть файл

@ -5,8 +5,7 @@
<RootNamespace>Microsoft.eShopOnContainers.BuildingBlocks.EventBus</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
<ItemGroup>
</ItemGroup>
</Project>

Просмотреть файл

@ -1,10 +1,10 @@
using Newtonsoft.Json;
using System;
using System;
using System.Text.Json.Serialization;
namespace Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Events
{
public record IntegrationEvent
{
{
public IntegrationEvent()
{
Id = Guid.NewGuid();
@ -18,10 +18,10 @@ namespace Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Events
CreationDate = createDate;
}
[JsonProperty]
[JsonInclude]
public Guid Id { get; private init; }
[JsonProperty]
[JsonInclude]
public DateTime CreationDate { get; private init; }
}
}

Просмотреть файл

@ -4,8 +4,6 @@ using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Abstractions;
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Events;
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Extensions;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Polly;
using Polly.Retry;
using RabbitMQ.Client;
@ -15,6 +13,7 @@ using System;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Text.Json;
namespace Microsoft.eShopOnContainers.BuildingBlocks.EventBusRabbitMQ
{
@ -89,9 +88,11 @@ namespace Microsoft.eShopOnContainers.BuildingBlocks.EventBusRabbitMQ
_logger.LogTrace("Declaring RabbitMQ exchange to publish event: {EventId}", @event.Id);
channel.ExchangeDeclare(exchange: BROKER_NAME, type: "direct");
var message = JsonConvert.SerializeObject(@event);
var body = Encoding.UTF8.GetBytes(message);
var body = JsonSerializer.SerializeToUtf8Bytes(@event, @event.GetType(), new JsonSerializerOptions
{
WriteIndented = true
});
policy.Execute(() =>
{
@ -272,8 +273,7 @@ namespace Microsoft.eShopOnContainers.BuildingBlocks.EventBusRabbitMQ
{
var handler = scope.ResolveOptional(subscription.HandlerType) as IDynamicIntegrationEventHandler;
if (handler == null) continue;
dynamic eventData = JObject.Parse(message);
using dynamic eventData = JsonDocument.Parse(message);
await Task.Yield();
await handler.Handle(eventData);
}
@ -282,7 +282,7 @@ namespace Microsoft.eShopOnContainers.BuildingBlocks.EventBusRabbitMQ
var handler = scope.ResolveOptional(subscription.HandlerType);
if (handler == null) continue;
var eventType = _subsManager.GetEventTypeByName(eventName);
var integrationEvent = JsonConvert.DeserializeObject(message, eventType);
var integrationEvent = JsonSerializer.Deserialize(message, eventType, new JsonSerializerOptions() { PropertyNameCaseInsensitive= true});
var concreteType = typeof(IIntegrationEventHandler<>).MakeGenericType(eventType);
await Task.Yield();

Просмотреть файл

@ -8,8 +8,7 @@
<ItemGroup>
<PackageReference Include="Autofac" Version="6.1.0" />
<PackageReference Include="Microsoft.CSharp" Version="4.7.0" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="5.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="5.0.0" />
<PackageReference Include="Polly" Version="7.2.1" />
<PackageReference Include="RabbitMQ.Client" Version="6.2.1" />
</ItemGroup>

Просмотреть файл

@ -5,11 +5,10 @@
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus;
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Abstractions;
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Events;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Microsoft.Extensions.Logging;
using System;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
public class EventBusServiceBus : IEventBus
@ -36,7 +35,7 @@
public void Publish(IntegrationEvent @event)
{
var eventName = @event.GetType().Name.Replace(INTEGRATION_EVENT_SUFFIX, "");
var jsonMessage = JsonConvert.SerializeObject(@event);
var jsonMessage = JsonSerializer.Serialize(@event);
var body = Encoding.UTF8.GetBytes(jsonMessage);
var message = new Message
@ -165,7 +164,8 @@
{
var handler = scope.ResolveOptional(subscription.HandlerType) as IDynamicIntegrationEventHandler;
if (handler == null) continue;
dynamic eventData = JObject.Parse(message);
using dynamic eventData = JsonDocument.Parse(message);
await handler.Handle(eventData);
}
else
@ -173,7 +173,7 @@
var handler = scope.ResolveOptional(subscription.HandlerType);
if (handler == null) continue;
var eventType = _subsManager.GetEventTypeByName(eventName);
var integrationEvent = JsonConvert.DeserializeObject(message, eventType);
var integrationEvent = JsonSerializer.Deserialize(message, eventType);
var concreteType = typeof(IIntegrationEventHandler<>).MakeGenericType(eventType);
await (Task)concreteType.GetMethod("Handle").Invoke(handler, new object[] { integrationEvent });
}

Просмотреть файл

@ -12,8 +12,7 @@
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="5.0.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="5.0.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="5.0.2" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="5.0.2" />
</ItemGroup>
<ItemGroup>

Просмотреть файл

@ -1,6 +1,6 @@
using Microsoft.eShopOnContainers.BuildingBlocks.EventBus.Events;
using Newtonsoft.Json;
using System;
using System.Text.Json;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
@ -13,8 +13,11 @@ namespace Microsoft.eShopOnContainers.BuildingBlocks.IntegrationEventLogEF
{
EventId = @event.Id;
CreationTime = @event.CreationDate;
EventTypeName = @event.GetType().FullName;
Content = JsonConvert.SerializeObject(@event);
EventTypeName = @event.GetType().FullName;
Content = JsonSerializer.Serialize(@event, @event.GetType(), new JsonSerializerOptions
{
WriteIndented = true
});
State = EventStateEnum.NotPublished;
TimesSent = 0;
TransactionId = transactionId.ToString();
@ -32,8 +35,8 @@ namespace Microsoft.eShopOnContainers.BuildingBlocks.IntegrationEventLogEF
public string TransactionId { get; private set; }
public IntegrationEventLogEntry DeserializeJsonContent(Type type)
{
IntegrationEvent = JsonConvert.DeserializeObject(Content, type) as IntegrationEvent;
{
IntegrationEvent = JsonSerializer.Deserialize(Content, type, new JsonSerializerOptions() { PropertyNameCaseInsensitive = true }) as IntegrationEvent;
return this;
}
}

Просмотреть файл

@ -29,8 +29,7 @@
<PackageReference Include="Microsoft.ApplicationInsights.Kubernetes" Version="1.1.3" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="5.0.2" />
<PackageReference Include="Microsoft.AspNetCore.Diagnostics.HealthChecks" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.HealthChecks" Version="1.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="5.0.2" />
<PackageReference Include="Microsoft.AspNetCore.HealthChecks" Version="1.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.AzureKeyVault" Version="3.1.11" />
<PackageReference Include="Microsoft.Extensions.Logging.AzureAppServices" Version="5.0.2" />
<PackageReference Include="Serilog.AspNetCore" Version="3.4.0" />

Просмотреть файл

@ -1,10 +1,10 @@
using Microsoft.eShopOnContainers.Services.Basket.API.Model;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using StackExchange.Redis;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Text.Json;
namespace Microsoft.eShopOnContainers.Services.Basket.API.Infrastructure.Repositories
{
@ -43,12 +43,15 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API.Infrastructure.Reposit
return null;
}
return JsonConvert.DeserializeObject<CustomerBasket>(data);
return JsonSerializer.Deserialize<CustomerBasket>(data, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
}
public async Task<CustomerBasket> UpdateBasketAsync(CustomerBasket basket)
{
var created = await _database.StringSetAsync(basket.BuyerId, JsonConvert.SerializeObject(basket));
var created = await _database.StringSetAsync(basket.BuyerId, JsonSerializer.Serialize(basket));
if (!created)
{

Просмотреть файл

@ -62,7 +62,7 @@ namespace Microsoft.eShopOnContainers.Services.Basket.API
}) // Added for functional tests
.AddApplicationPart(typeof(BasketController).Assembly)
.AddNewtonsoftJson();
.AddJsonOptions(options => options.JsonSerializerOptions.WriteIndented = true);
services.AddSwaggerGen(options =>
{

Просмотреть файл

@ -1,9 +1,9 @@
using Basket.FunctionalTests.Base;
using Microsoft.eShopOnContainers.Services.Basket.API.Model;
using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using Xunit;
@ -68,7 +68,7 @@ namespace Basket.FunctionalTests
Quantity = 1
});
return JsonConvert.SerializeObject(order);
return JsonSerializer.Serialize(order);
}
string BuildCheckout()
@ -89,7 +89,7 @@ namespace Basket.FunctionalTests
RequestId = Guid.NewGuid()
};
return JsonConvert.SerializeObject(checkoutBasket);
return JsonSerializer.Serialize(checkoutBasket);
}
}
}

Просмотреть файл

@ -54,8 +54,7 @@
<PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.16.0" />
<PackageReference Include="Microsoft.ApplicationInsights.DependencyCollector" Version="2.16.0" />
<PackageReference Include="Microsoft.ApplicationInsights.Kubernetes" Version="1.1.3" />
<PackageReference Include="Microsoft.AspNetCore.HealthChecks" Version="1.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="5.0.2" />
<PackageReference Include="Microsoft.AspNetCore.HealthChecks" Version="1.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.AzureKeyVault" Version="3.1.11" />
<PackageReference Include="Microsoft.Extensions.Logging.AzureAppServices" Version="5.0.2" />
<PackageReference Include="Serilog.AspNetCore" Version="3.4.0" />

Просмотреть файл

@ -140,7 +140,8 @@ namespace Microsoft.eShopOnContainers.Services.Catalog.API
services.AddControllers(options =>
{
options.Filters.Add(typeof(HttpGlobalExceptionFilter));
}).AddNewtonsoftJson();
})
.AddJsonOptions(options => options.JsonSerializerOptions.WriteIndented = true);
services.AddCors(options =>
{

Просмотреть файл

@ -7,7 +7,7 @@ namespace Ordering.API.Application.IntegrationEvents.Events
// An Integration Event is an event that can cause side effects to other microsrvices, Bounded-Contexts or external systems.
public record OrderStartedIntegrationEvent : IntegrationEvent
{
public string UserId { get; set; }
public string UserId { get; init; }
public OrderStartedIntegrationEvent(string userId)
=> UserId = userId;

Просмотреть файл

@ -5,15 +5,15 @@ using System;
namespace Ordering.API.Application.IntegrationEvents.Events
{
public record UserCheckoutAcceptedIntegrationEvent : IntegrationEvent
{
{
public string UserId { get; }
public string UserName { get; }
public string City { get; set; }
public string Street { get; set; }
public string State { get; set; }
public string Country { get; set; }

Просмотреть файл

@ -7,10 +7,10 @@ namespace Ordering.API.Application.Models
public string BuyerId { get; set; }
public List<BasketItem> Items { get; set; }
public CustomerBasket(string customerId)
public CustomerBasket(string buyerId, List<BasketItem> items)
{
BuyerId = customerId;
Items = new List<BasketItem>();
BuyerId = buyerId;
Items = items;
}
}
}

Просмотреть файл

@ -54,8 +54,7 @@
<PackageReference Include="Microsoft.ApplicationInsights.Kubernetes" Version="1.1.3" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="5.0.2" />
<PackageReference Include="Microsoft.AspNetCore.Diagnostics.HealthChecks" Version="2.2.0" />
<PackageReference Include="Microsoft.AspNetCore.HealthChecks" Version="1.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="5.0.2" />
<PackageReference Include="Microsoft.AspNetCore.HealthChecks" Version="1.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.AzureKeyVault" Version="3.1.11" />
<PackageReference Include="Microsoft.Extensions.Logging.AzureAppServices" Version="5.0.2" />
<PackageReference Include="Microsoft.NETCore.Platforms" Version="5.0.0" />

Просмотреть файл

@ -172,9 +172,8 @@
})
// Added for functional tests
.AddApplicationPart(typeof(OrdersController).Assembly)
.AddNewtonsoftJson()
.SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
;
.AddJsonOptions(options => options.JsonSerializerOptions.WriteIndented = true)
.SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
services.AddCors(options =>
{

Просмотреть файл

@ -1,7 +1,7 @@
using Newtonsoft.Json;
using System.Net;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using WebMVC.Services.ModelDTOs;
using Xunit;
@ -55,7 +55,7 @@ namespace Ordering.FunctionalTests
{
OrderNumber = "-1"
};
return JsonConvert.SerializeObject(order);
return JsonSerializer.Serialize(order);
}
}
}

Просмотреть файл

@ -1,5 +1,5 @@
using Newtonsoft.Json;
using System;
using System;
using System.Text.Json;
namespace Webhooks.API.Model
{
@ -15,9 +15,7 @@ namespace Webhooks.API.Model
{
When = DateTime.UtcNow;
Type = hookType.ToString();
Payload = JsonConvert.SerializeObject(data);
Payload = JsonSerializer.Serialize(data);
}
}
}

Просмотреть файл

@ -1,10 +1,10 @@
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using Webhooks.API.Model;
@ -23,7 +23,7 @@ namespace Webhooks.API.Services
public async Task SendAll(IEnumerable<WebhookSubscription> receivers, WebhookData data)
{
var client = _httpClientFactory.CreateClient();
var json = JsonConvert.SerializeObject(data);
var json = JsonSerializer.Serialize(data);
var tasks = receivers.Select(r => OnSendData(r, json, client));
await Task.WhenAll(tasks.ToArray());
}

Просмотреть файл

@ -3,12 +3,12 @@ using FunctionalTests.Services.Catalog;
using Microsoft.eShopOnContainers.Services.Basket.API.Model;
using Microsoft.eShopOnContainers.Services.Catalog.API.Model;
using Microsoft.eShopOnContainers.Services.Catalog.API.ViewModel;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using Xunit;
@ -35,7 +35,7 @@ namespace FunctionalTests.Services
var basket = ComposeBasket(userId, originalCatalogProducts.Data.Take(3));
var res = await basketClient.PostAsync(
BasketScenariosBase.Post.CreateBasket,
new StringContent(JsonConvert.SerializeObject(basket), UTF8Encoding.UTF8, "application/json")
new StringContent(JsonSerializer.Serialize(basket), UTF8Encoding.UTF8, "application/json")
);
// WHEN the price of one product is modified in the catalog
@ -74,7 +74,10 @@ namespace FunctionalTests.Services
{
//get the basket and verify that the price of the modified product is updated
var basketGetResponse = await basketClient.GetAsync(BasketScenariosBase.Get.GetBasketByCustomer(userId));
var basketUpdated = JsonConvert.DeserializeObject<CustomerBasket>(await basketGetResponse.Content.ReadAsStringAsync());
var basketUpdated = JsonSerializer.Deserialize<CustomerBasket>(await basketGetResponse.Content.ReadAsStringAsync(), new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
itemUpdated = basketUpdated.Items.Single(pr => pr.ProductId == productId);
@ -96,14 +99,17 @@ namespace FunctionalTests.Services
{
var response = await catalogClient.GetAsync(CatalogScenariosBase.Get.Items);
var items = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<PaginatedItemsViewModel<CatalogItem>>(items);
return JsonSerializer.Deserialize<PaginatedItemsViewModel<CatalogItem>>(items, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
}
private string ChangePrice(BasketItem itemToModify, decimal newPrice, PaginatedItemsViewModel<CatalogItem> catalogProducts)
{
var catalogProduct = catalogProducts.Data.Single(pr => pr.Id == itemToModify.ProductId);
catalogProduct.Price = newPrice;
return JsonConvert.SerializeObject(catalogProduct);
return JsonSerializer.Serialize(catalogProduct);
}
private CustomerBasket ComposeBasket(string customerId, IEnumerable<CatalogItem> items)

Просмотреть файл

@ -2,8 +2,8 @@
using FunctionalTests.Services.Basket;
using Microsoft.eShopOnContainers.Services.Basket.API.Model;
using Microsoft.eShopOnContainers.WebMVC.ViewModels;
using Newtonsoft.Json;
using System;
using System.Text.Json;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
@ -53,7 +53,10 @@ namespace FunctionalTests.Services.Ordering
async Task<Order> TryGetOrder(string orderNumber, HttpClient orderClient)
{
var ordersGetResponse = await orderClient.GetStringAsync(OrderingScenariosBase.Get.Orders);
var orders = JsonConvert.DeserializeObject<List<Order>>(ordersGetResponse);
var orders = JsonSerializer.Deserialize<List<Order>>(ordersGetResponse, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
return orders.Single(o => o.OrderNumber == orderNumber);
}
@ -67,7 +70,10 @@ namespace FunctionalTests.Services.Ordering
{
//get the orders and verify that the new order has been created
var ordersGetResponse = await orderClient.GetStringAsync(OrderingScenariosBase.Get.Orders);
var orders = JsonConvert.DeserializeObject<List<Order>>(ordersGetResponse);
var orders = JsonSerializer.Deserialize<List<Order>>(ordersGetResponse, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
if (orders == null || orders.Count == 0)
{
@ -79,7 +85,11 @@ namespace FunctionalTests.Services.Ordering
var lastOrder = orders.OrderByDescending(o => o.Date).First();
int.TryParse(lastOrder.OrderNumber, out int id);
var orderDetails = await orderClient.GetStringAsync(OrderingScenariosBase.Get.OrderBy(id));
order = JsonConvert.DeserializeObject<Order>(orderDetails);
order = JsonSerializer.Deserialize<Order>(orderDetails, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
order.City = city;
if (IsOrderCreated(order, city))
@ -110,7 +120,7 @@ namespace FunctionalTests.Services.Ordering
Quantity = 1
}
};
return JsonConvert.SerializeObject(order);
return JsonSerializer.Serialize(order);
}
string BuildCancelOrder(string orderId)
@ -119,7 +129,7 @@ namespace FunctionalTests.Services.Ordering
{
OrderNumber = orderId
};
return JsonConvert.SerializeObject(order);
return JsonSerializer.Serialize(order);
}
string BuildCheckout(string cityExpected)
@ -140,7 +150,7 @@ namespace FunctionalTests.Services.Ordering
RequestId = Guid.NewGuid()
};
return JsonConvert.SerializeObject(checkoutBasket);
return JsonSerializer.Serialize(checkoutBasket);
}
}
}

Просмотреть файл

@ -2,9 +2,9 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.eShopOnContainers.WebMVC.Services;
using Microsoft.eShopOnContainers.WebMVC.ViewModels;
using Newtonsoft.Json;
using System.Net.Http;
using System.Threading.Tasks;
using System.Text.Json;
namespace WebMVC.Controllers
{
@ -40,7 +40,7 @@ namespace WebMVC.Controllers
BasketId = _appUserParser.Parse(User).Id
};
var content = new StringContent(JsonConvert.SerializeObject(payload), System.Text.Encoding.UTF8, "application/json");
var content = new StringContent(JsonSerializer.Serialize(payload), System.Text.Encoding.UTF8, "application/json");
var response = await _client.CreateClient(nameof(IBasketService))

Просмотреть файл

@ -1,17 +1,20 @@
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using System.Text.Json;
public static class SessionExtensions
{
public static void SetObject(this ISession session, string key, object value) =>
session.SetString(key, JsonConvert.SerializeObject(value));
session.SetString(key,JsonSerializer.Serialize(value));
public static T GetObject<T>(this ISession session, string key)
{
var value = session.GetString(key);
return value == null ? default(T) : JsonConvert.DeserializeObject<T>(value);
return value == null ? default(T) :JsonSerializer.Deserialize<T>(value, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
}
}

Просмотреть файл

@ -1,13 +1,13 @@
using Microsoft.eShopOnContainers.WebMVC.ViewModels;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using WebMVC.Infrastructure;
using WebMVC.Services.ModelDTOs;
using System.Text.Json;
namespace Microsoft.eShopOnContainers.WebMVC.Services
{
@ -38,14 +38,17 @@ namespace Microsoft.eShopOnContainers.WebMVC.Services
var responseString = await response.Content.ReadAsStringAsync();
return string.IsNullOrEmpty(responseString) ?
new Basket() { BuyerId = user.Id } :
JsonConvert.DeserializeObject<Basket>(responseString);
JsonSerializer.Deserialize<Basket>(responseString, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
}
public async Task<Basket> UpdateBasket(Basket basket)
{
var uri = API.Basket.UpdateBasket(_basketByPassUrl);
var basketContent = new StringContent(JsonConvert.SerializeObject(basket), System.Text.Encoding.UTF8, "application/json");
var basketContent = new StringContent(JsonSerializer.Serialize(basket), System.Text.Encoding.UTF8, "application/json");
var response = await _apiClient.PostAsync(uri, basketContent);
@ -57,8 +60,8 @@ namespace Microsoft.eShopOnContainers.WebMVC.Services
public async Task Checkout(BasketDTO basket)
{
var uri = API.Basket.CheckoutBasket(_basketByPassUrl);
var basketContent = new StringContent(JsonConvert.SerializeObject(basket), System.Text.Encoding.UTF8, "application/json");
var basketContent = new StringContent(JsonSerializer.Serialize(basket), System.Text.Encoding.UTF8, "application/json");
_logger.LogInformation("Uri chechout {uri}", uri);
var response = await _apiClient.PostAsync(uri, basketContent);
@ -80,7 +83,7 @@ namespace Microsoft.eShopOnContainers.WebMVC.Services
}).ToArray()
};
var basketContent = new StringContent(JsonConvert.SerializeObject(basketUpdate), System.Text.Encoding.UTF8, "application/json");
var basketContent = new StringContent(JsonSerializer.Serialize(basketUpdate), System.Text.Encoding.UTF8, "application/json");
var response = await _apiClient.PutAsync(uri, basketContent);
@ -88,7 +91,10 @@ namespace Microsoft.eShopOnContainers.WebMVC.Services
var jsonResponse = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<Basket>(jsonResponse);
return JsonSerializer.Deserialize<Basket>(jsonResponse, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
}
public async Task<Order> GetOrderDraft(string basketId)
@ -97,7 +103,10 @@ namespace Microsoft.eShopOnContainers.WebMVC.Services
var responseString = await _apiClient.GetStringAsync(uri);
var response = JsonConvert.DeserializeObject<Order>(responseString);
var response = JsonSerializer.Deserialize<Order>(responseString, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
return response;
}
@ -113,7 +122,7 @@ namespace Microsoft.eShopOnContainers.WebMVC.Services
Quantity = 1
};
var basketContent = new StringContent(JsonConvert.SerializeObject(newItem), System.Text.Encoding.UTF8, "application/json");
var basketContent = new StringContent(JsonSerializer.Serialize(newItem), System.Text.Encoding.UTF8, "application/json");
var response = await _apiClient.PostAsync(uri, basketContent);
}

Просмотреть файл

@ -2,12 +2,11 @@
using Microsoft.eShopOnContainers.WebMVC.ViewModels;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using WebMVC.Infrastructure;
using System.Text.Json;
namespace Microsoft.eShopOnContainers.WebMVC.Services
{
@ -34,7 +33,10 @@ namespace Microsoft.eShopOnContainers.WebMVC.Services
var responseString = await _httpClient.GetStringAsync(uri);
var catalog = JsonConvert.DeserializeObject<Catalog>(responseString);
var catalog = JsonSerializer.Deserialize<Catalog>(responseString, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
return catalog;
}
@ -48,15 +50,15 @@ namespace Microsoft.eShopOnContainers.WebMVC.Services
var items = new List<SelectListItem>();
items.Add(new SelectListItem() { Value = null, Text = "All", Selected = true });
using var brands = JsonDocument.Parse(responseString);
var brands = JArray.Parse(responseString);
foreach (var brand in brands.Children<JObject>())
foreach (JsonElement brand in brands.RootElement.EnumerateArray())
{
items.Add(new SelectListItem()
{
Value = brand.Value<string>("id"),
Text = brand.Value<string>("brand")
Value = brand.GetProperty("id").ToString(),
Text = brand.GetProperty("brand").ToString()
});
}
@ -71,14 +73,15 @@ namespace Microsoft.eShopOnContainers.WebMVC.Services
var items = new List<SelectListItem>();
items.Add(new SelectListItem() { Value = null, Text = "All", Selected = true });
using var catalogTypes = JsonDocument.Parse(responseString);
var brands = JArray.Parse(responseString);
foreach (var brand in brands.Children<JObject>())
foreach (JsonElement catalogType in catalogTypes.RootElement.EnumerateArray())
{
items.Add(new SelectListItem()
{
Value = brand.Value<string>("id"),
Text = brand.Value<string>("type")
Value = catalogType.GetProperty("id").ToString(),
Text = catalogType.GetProperty("type").ToString()
});
}

Просмотреть файл

@ -1,12 +1,12 @@
using Microsoft.eShopOnContainers.WebMVC.ViewModels;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using WebMVC.Infrastructure;
using WebMVC.Services.ModelDTOs;
using System.Text.Json;
namespace Microsoft.eShopOnContainers.WebMVC.Services
{
@ -31,7 +31,10 @@ namespace Microsoft.eShopOnContainers.WebMVC.Services
var responseString = await _httpClient.GetStringAsync(uri);
var response = JsonConvert.DeserializeObject<Order>(responseString);
var response = JsonSerializer.Deserialize<Order>(responseString, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
return response;
}
@ -42,7 +45,10 @@ namespace Microsoft.eShopOnContainers.WebMVC.Services
var responseString = await _httpClient.GetStringAsync(uri);
var response = JsonConvert.DeserializeObject<List<Order>>(responseString);
var response = JsonSerializer.Deserialize<List<Order>>(responseString, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
return response;
}
@ -57,7 +63,7 @@ namespace Microsoft.eShopOnContainers.WebMVC.Services
};
var uri = API.Order.CancelOrder(_remoteServiceBaseUrl);
var orderContent = new StringContent(JsonConvert.SerializeObject(order), System.Text.Encoding.UTF8, "application/json");
var orderContent = new StringContent(JsonSerializer.Serialize(order), System.Text.Encoding.UTF8, "application/json");
var response = await _httpClient.PutAsync(uri, orderContent);
@ -77,7 +83,7 @@ namespace Microsoft.eShopOnContainers.WebMVC.Services
};
var uri = API.Order.ShipOrder(_remoteServiceBaseUrl);
var orderContent = new StringContent(JsonConvert.SerializeObject(order), System.Text.Encoding.UTF8, "application/json");
var orderContent = new StringContent(JsonSerializer.Serialize(order), System.Text.Encoding.UTF8, "application/json");
var response = await _httpClient.PutAsync(uri, orderContent);

Просмотреть файл

@ -3,7 +3,7 @@
public record BasketItem
{
public string Id { get; init; }
public string ProductId { get; init; }
public int ProductId { get; init; }
public string ProductName { get; init; }
public decimal UnitPrice { get; init; }
public decimal OldUnitPrice { get; init; }

Просмотреть файл

@ -0,0 +1,34 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
namespace Microsoft.eShopOnContainers.WebMVC.ViewModels
{
public class NumberToStringConverter : JsonConverter<string>
{
public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType == JsonTokenType.Number)
{
var numberValue = reader.GetInt32();
return numberValue.ToString();
}
else if (reader.TokenType == JsonTokenType.String)
{
return reader.GetString();
}
else
{
throw new JsonException();
}
}
public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options)
{
writer.WriteStringValue(value);
}
}
}

Просмотреть файл

@ -1,16 +1,17 @@
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.eShopOnContainers.WebMVC.ViewModels.Annotations;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Text.Json.Serialization;
using WebMVC.Services.ModelDTOs;
namespace Microsoft.eShopOnContainers.WebMVC.ViewModels
{
public class Order
{
{
[JsonConverter(typeof(NumberToStringConverter))]
public string OrderNumber { get; set; }
public DateTime Date { get; set; }
@ -53,11 +54,8 @@ namespace Microsoft.eShopOnContainers.WebMVC.ViewModels
public List<SelectListItem> ActionCodeSelectList =>
GetActionCodesByCurrentState();
// See the property initializer syntax below. This
// initializes the compiler generated field for this
// auto-implemented property.
public List<OrderItem> OrderItems { get; } = new List<OrderItem>();
public List<OrderItem> OrderItems { get; set; }
[Required]
public Guid RequestId { get; set; }

Просмотреть файл

@ -94,8 +94,7 @@
<PackageReference Include="Microsoft.ApplicationInsights.Kubernetes" Version="1.1.3" />
<PackageReference Include="Microsoft.AspNetCore.DataProtection.StackExchangeRedis" Version="5.0.2" />
<PackageReference Include="Microsoft.AspNetCore.Diagnostics.HealthChecks" Version="2.2.0" />
<PackageReference Include="Microsoft.Extensions.Logging.AzureAppServices" Version="5.0.2" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
<PackageReference Include="Microsoft.Extensions.Logging.AzureAppServices" Version="5.0.2" />
<PackageReference Include="Serilog.AspNetCore" Version="3.4.0" />
<PackageReference Include="Serilog.Sinks.Console" Version="4.0.0-dev-00834" />
</ItemGroup>

Просмотреть файл

@ -2,12 +2,12 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Threading.Tasks;
using WebhookClient.Models;
using System.Text.Json;
namespace WebhookClient.Pages
{
@ -66,7 +66,7 @@ namespace WebhookClient.Pages
}
else
{
RequestBodyJson = JsonConvert.SerializeObject(payload);
RequestBodyJson = JsonSerializer.Serialize(payload);
ResponseCode = (int)response.StatusCode;
ResponseMessage = response.ReasonPhrase;
GrantUrl = granturl;

Просмотреть файл

@ -1,9 +1,9 @@
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using WebhookClient.Models;
using System.Text.Json;
namespace WebhookClient.Services
{
@ -22,7 +22,10 @@ namespace WebhookClient.Services
var client = _httpClientFactory.CreateClient("GrantClient");
var response = await client.GetAsync(_settings.WebhooksUrl + "/api/v1/webhooks");
var json = await response.Content.ReadAsStringAsync();
var subscriptions = JsonConvert.DeserializeObject<IEnumerable<WebhookResponse>>(json);
var subscriptions = JsonSerializer.Deserialize<IEnumerable<WebhookResponse>>(json, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
return subscriptions;
}
}