Skip to content

Commit 467b173

Browse files
committed
Replace Newtonsoft.Json with the new .Net JsonSerializer.
1 parent 23f31aa commit 467b173

File tree

82 files changed

+542
-474
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

82 files changed

+542
-474
lines changed

Microsoft.Toolkit.Services/Microsoft.Toolkit.Services.csproj

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@
3030
</ItemGroup>
3131

3232
<ItemGroup>
33-
<PackageReference Include="Newtonsoft.Json" Version="10.0.3" />
33+
<PackageReference Include="System.Text.Json" Version="4.7.2" />
3434
<PackageReference Include="System.Net.Http" Version="4.3.4" />
3535
</ItemGroup>
3636

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
<?xml version="1.0" encoding="utf-8"?>
2+
<Directives xmlns="http://schemas.microsoft.com/netfx/2013/01/metadata">
3+
<Library Name="Microsoft.Toolkit.Services">
4+
<Namespace Name="System.Text.Json.Serialization.Converters" Dynamic="Required All"/>
5+
</Library>
6+
</Directives>

Microsoft.Toolkit.Services/Services/LinkedIn/LinkedInDataProvider.cs

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,9 @@
77
using System.Diagnostics;
88
using System.Net.Http;
99
using System.Text;
10+
using System.Text.Json;
1011
using System.Threading.Tasks;
1112
using Microsoft.Toolkit.Services.Core;
12-
using Newtonsoft.Json.Linq;
1313

1414
#if WINRT
1515
using Microsoft.Toolkit.Services.PlatformSpecific.Uwp;
@@ -81,7 +81,8 @@ public LinkedInDataProvider(LinkedInOAuthTokens tokens, LinkedInPermissions requ
8181
throw new ArgumentException("Missing callback uri");
8282
}
8383

84-
if (!Enum.IsDefined(typeof(LinkedInPermissions), requiredPermissions))
84+
// Check if outside the bounds of the LinkedInPermissions Enum
85+
if (requiredPermissions < 0 || requiredPermissions > (LinkedInPermissions)15)
8586
{
8687
throw new ArgumentException("Error retrieving required permissions");
8788
}
@@ -278,9 +279,14 @@ private async Task<string> GetAccessTokenAsync(LinkedInOAuthTokens tokens, strin
278279
{
279280
using (var response = await client.SendAsync(request).ConfigureAwait(false))
280281
{
281-
var jsonString = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
282-
var json = JObject.Parse(jsonString);
283-
return json.GetValue("access_token").Value<string>();
282+
using (var jsonStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
283+
{
284+
using (var jsonDoc = await JsonDocument.ParseAsync(jsonStream).ConfigureAwait(false))
285+
{
286+
var value = jsonDoc.RootElement.GetProperty("access_token");
287+
return value.GetString();
288+
}
289+
}
284290
}
285291
}
286292
}

Microsoft.Toolkit.Services/Services/LinkedIn/LinkedInParser.cs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
// See the LICENSE file in the project root for more information.
44

55
using System.Collections.Generic;
6-
using Newtonsoft.Json;
6+
using System.Text.Json;
77

88
namespace Microsoft.Toolkit.Services.LinkedIn
99
{
@@ -24,11 +24,11 @@ public IEnumerable<T> Parse(string data)
2424

2525
try
2626
{
27-
results = JsonConvert.DeserializeObject<List<T>>(data);
27+
results = JsonSerializer.Deserialize<List<T>>(data);
2828
}
29-
catch (JsonSerializationException)
29+
catch (JsonException)
3030
{
31-
T linkedInResult = JsonConvert.DeserializeObject<T>(data);
31+
T linkedInResult = JsonSerializer.Deserialize<T>(data);
3232
results = new List<T> { linkedInResult };
3333
}
3434

@@ -42,7 +42,7 @@ public IEnumerable<T> Parse(string data)
4242
/// <returns>Returns string data.</returns>
4343
public string Parse(T dataToShare)
4444
{
45-
return JsonConvert.SerializeObject(dataToShare, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
45+
return JsonSerializer.Serialize(dataToShare, typeof(T), new JsonSerializerOptions { IgnoreNullValues = true });
4646
}
4747
}
4848
}

Microsoft.Toolkit.Services/Services/MicrosoftTranslator/AzureAuthToken.cs

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,8 @@
44

55
using System;
66
using System.Net.Http;
7+
using System.Text.Json;
78
using System.Threading.Tasks;
8-
using Newtonsoft.Json;
99

1010
namespace Microsoft.Toolkit.Services.MicrosoftTranslator
1111
{
@@ -24,6 +24,9 @@ internal class AzureAuthToken
2424
/// </summary>
2525
private static readonly Uri ServiceUrl = new Uri("https://api.cognitive.microsoft.com/sts/v1.0/issueToken");
2626

27+
// TODO
28+
// private static readonly Uri ServiceUrl = new Uri(THIS SHOULD BE A PARAMETER NOW);
29+
2730
/// <summary>
2831
/// After obtaining a valid token, this class will cache it for this duration.
2932
/// Use a duration of 8 minutes, which is less than the actual token lifetime of 10 minutes.
@@ -99,8 +102,8 @@ public async Task<string> GetAccessTokenAsync()
99102

100103
if (!response.IsSuccessStatusCode)
101104
{
102-
var error = JsonConvert.DeserializeObject<ErrorResponse>(content);
103-
throw new TranslatorServiceException(error.Message);
105+
var error = JsonSerializer.Deserialize<ErrorResponse>(content);
106+
throw new TranslatorServiceException(error?.Error?.Message);
104107
}
105108

106109
_storedTokenTime = DateTime.Now;

Microsoft.Toolkit.Services/Services/MicrosoftTranslator/ErrorResponse.cs

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,21 +2,27 @@
22
// The .NET Foundation licenses this file to you under the MIT license.
33
// See the LICENSE file in the project root for more information.
44

5+
using System.Text.Json.Serialization;
6+
57
namespace Microsoft.Toolkit.Services.MicrosoftTranslator
68
{
9+
#pragma warning disable SA1402 // File may only contain a single type
710
/// <summary>
811
/// Holds information about an error occurred while accessing Microsoft Translator Service.
912
/// </summary>
1013
internal class ErrorResponse
14+
{
15+
[JsonPropertyName("error")]
16+
public Error Error { get; set; }
17+
}
18+
19+
internal class Error
1120
{
1221
/// <summary>
1322
/// Gets or sets the error message.
1423
/// </summary>
24+
[JsonPropertyName("message")]
1525
public string Message { get; set; }
16-
17-
/// <summary>
18-
/// Gets or sets the HTTP status code.
19-
/// </summary>
20-
public int StatusCode { get; set; }
2126
}
27+
#pragma warning restore SA1402 // File may only contain a single type
2228
}

Microsoft.Toolkit.Services/Services/MicrosoftTranslator/ServiceLanguage.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
// The .NET Foundation licenses this file to you under the MIT license.
33
// See the LICENSE file in the project root for more information.
44

5-
using Newtonsoft.Json;
5+
using System.Text.Json.Serialization;
66

77
namespace Microsoft.Toolkit.Services.MicrosoftTranslator
88
{
@@ -30,7 +30,7 @@ public class ServiceLanguage
3030
/// <summary>
3131
/// Gets the directionality, which is rtl for right-to-left languages or ltr for left-to-right languages.
3232
/// </summary>
33-
[JsonProperty("dir")]
33+
[JsonPropertyName("dir")]
3434
public string Directionality { get; }
3535

3636
/// <summary>

Microsoft.Toolkit.Services/Services/MicrosoftTranslator/TranslatorService.cs

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,8 @@
88
using System.Linq;
99
using System.Net.Http;
1010
using System.Net.Http.Headers;
11+
using System.Text.Json;
1112
using System.Threading.Tasks;
12-
using Newtonsoft.Json;
13-
using Newtonsoft.Json.Linq;
1413

1514
namespace Microsoft.Toolkit.Services.MicrosoftTranslator
1615
{
@@ -113,7 +112,7 @@ public async Task<IEnumerable<DetectedLanguageResponse>> DetectLanguagesWithResp
113112
var response = await client.SendAsync(request).ConfigureAwait(false);
114113
var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
115114

116-
var responseContent = JsonConvert.DeserializeObject<IEnumerable<DetectedLanguageResponse>>(content);
115+
var responseContent = JsonSerializer.Deserialize<IEnumerable<DetectedLanguageResponse>>(content);
117116
return responseContent;
118117
}
119118
}
@@ -144,8 +143,8 @@ public async Task<IEnumerable<ServiceLanguage>> GetLanguageNamesAsync(string lan
144143
var response = await client.SendAsync(request).ConfigureAwait(false);
145144
var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
146145

147-
var jsonContent = JToken.Parse(content)["translation"];
148-
var responseContent = JsonConvert.DeserializeObject<Dictionary<string, ServiceLanguage>>(jsonContent.ToString()).ToList();
146+
var jsonContent = JsonDocument.Parse(content).RootElement.GetProperty("translation");
147+
var responseContent = JsonSerializer.Deserialize<Dictionary<string, ServiceLanguage>>(jsonContent.ToString()).ToList();
149148
responseContent.ForEach(r => r.Value.Code = r.Key);
150149

151150
return responseContent.Select(r => r.Value).OrderBy(r => r.Name).ToList();
@@ -221,7 +220,7 @@ public async Task<IEnumerable<TranslationResponse>> TranslateWithResponseAsync(I
221220
var response = await client.SendAsync(request).ConfigureAwait(false);
222221
var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
223222

224-
var responseContent = JsonConvert.DeserializeObject<IEnumerable<TranslationResponse>>(content);
223+
var responseContent = JsonSerializer.Deserialize<IEnumerable<TranslationResponse>>(content);
225224
return responseContent;
226225
}
227226
}
@@ -254,7 +253,7 @@ private HttpRequestMessage CreateHttpRequest(string uriString, HttpMethod method
254253

255254
if (content != null)
256255
{
257-
var jsonRequest = JsonConvert.SerializeObject(content);
256+
var jsonRequest = JsonSerializer.Serialize(content);
258257
var requestContent = new StringContent(jsonRequest, System.Text.Encoding.UTF8, JsonMediaType);
259258
request.Content = requestContent;
260259
}

0 commit comments

Comments
 (0)