Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: Updating to system.text.json #83

Draft
wants to merge 1 commit into
base: development
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .talismanrc
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
fileignoreconfig:
- filename: Contentstack.Core/Internals/HttpRequestHandler.cs
checksum: 93c1659f3bc7527956f0fd12db46441297fac3a4366d273bcbb3425d2351300e
checksum: 29bb8548d65cdc5800fc939e526797bb3515f528d8082a58a0c9c6215dec1651
- filename: Contentstack.Core/Models/Entry.cs
checksum: 79320b005882981fd7c79fe73832f28284db686927942e46b422ac9e88405023
- filename: Contentstack.Core/ContentstackClient.cs
Expand Down
6 changes: 2 additions & 4 deletions Contentstack.Core/Configuration/LivePreviewConfig.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
using System;
using System.Collections;
using Newtonsoft.Json.Linq;
using System.Text.Json;

namespace Contentstack.Core.Configuration
{
Expand All @@ -13,6 +11,6 @@ public class LivePreviewConfig
internal string LivePreview { get; set; }
internal string ContentTypeUID { get; set; }
internal string EntryUID { get; set; }
internal JObject PreviewResponse { get; set; }
internal JsonElement PreviewResponse { get; set; }
}
}
3 changes: 1 addition & 2 deletions Contentstack.Core/Contentstack.Core.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFrameworks>netstandard2.0;net47;net472;</TargetFrameworks>
<TargetFrameworks>net7.0</TargetFrameworks>
<PackageId>contentstack.csharp</PackageId>
<Authors>Contentstack</Authors>
<Description>.NET SDK for the Contentstack Content Delivery API.</Description>
Expand All @@ -28,7 +28,6 @@
<AllowUnsafeBlocks></AllowUnsafeBlocks>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Microsoft.Extensions.Options" Version="8.0.2" />
<PackageReference Include="Markdig" Version="0.36.2" />
<PackageReference Include="contentstack.utils" Version="1.0.5" />
Expand Down
67 changes: 33 additions & 34 deletions Contentstack.Core/ContentstackClient.cs
Original file line number Diff line number Diff line change
@@ -1,18 +1,17 @@
using System;
using System.Collections;
using System.Collections.Generic;
using Contentstack.Core.Internals;
using Contentstack.Core.Configuration;
using Microsoft.Extensions.Options;
using Contentstack.Core.Models;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Net;
using System.IO;
using System.Collections;
using Contentstack.Utils;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using Contentstack.Core.Configuration;
using Contentstack.Core.Interfaces;
using Contentstack.Core.Internals;
using Contentstack.Core.Models;
using Microsoft.Extensions.Options;

namespace Contentstack.Core
{
Expand All @@ -24,7 +23,16 @@ public class ContentstackClient
/// <summary>
/// Gets or sets the settings that should be used for deserialization.
/// </summary>
public JsonSerializerSettings SerializerSettings { get; set; } = new JsonSerializerSettings();
public JsonSerializerOptions SerializerSettings { get; set; } = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
Converters = {
new JsonStringEnumConverter(),
new CustomUtcDateTimeConverter(),
new CustomNullableUtcDateTimeConverter(),
}
};

#region Internal Variables

Expand All @@ -35,7 +43,6 @@ internal string StackApiKey
}
private ContentstackOptions _options;

internal JsonSerializer Serializer => JsonSerializer.Create(SerializerSettings);
internal string _SyncUrl
{
get
Expand Down Expand Up @@ -133,10 +140,6 @@ public ContentstackClient(IOptions<ContentstackOptions> options)
throw new InvalidOperationException("Add PreviewToken or ManagementToken in LivePreviewConfig");
}
}
this.SerializerSettings.DateParseHandling = DateParseHandling.None;
this.SerializerSettings.DateFormatHandling = DateFormatHandling.IsoDateFormat;
this.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
this.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;

foreach (Type t in CSJsonConverterAttribute.GetCustomAttribute(typeof(CSJsonConverterAttribute)))
{
Expand Down Expand Up @@ -209,22 +212,18 @@ internal static ContentstackException GetContentstackError(Exception ex)
using (var reader = new StreamReader(stream))
{
errorMessage = reader.ReadToEnd();
JObject data = JObject.Parse(errorMessage.Replace("\r\n", ""));
var data = JsonSerializer.Deserialize<JsonElement>(errorMessage);

JToken token = data["error_code"];
if (token != null)
errorCode = token.Value<int>();
if (data.TryGetProperty("error_code", out var token))
errorCode = token.GetInt32();

token = data["error_message"];
if (token != null)
errorMessage = token.Value<string>();
if (data.TryGetProperty("error_message", out token))
errorMessage = token.GetString();

token = data["errors"];
if (token != null)
errors = token.ToObject<Dictionary<string, object>>();
if (data.TryGetProperty("errors", out token))
errors = JsonSerializer.Deserialize<Dictionary<string, object>>(token.GetRawText());

var response = exResp as HttpWebResponse;
if (response != null)
if (exResp is HttpWebResponse response)
statusCode = response.StatusCode;
}
}
Expand Down Expand Up @@ -326,8 +325,8 @@ public async Task<IList> GetContentTypes(Dictionary<string, object> param = null
{
HttpRequestHandler RequestHandler = new HttpRequestHandler(this);
var outputResult = await RequestHandler.ProcessRequest(_Url, headers, mainJson, Branch: this.Config.Branch, timeout: this.Config.Timeout, proxy: this.Config.Proxy);
JObject data = JsonConvert.DeserializeObject<JObject>(outputResult.Replace("\r\n", ""), this.SerializerSettings);
IList contentTypes = (IList)data["content_types"];
var data = JsonSerializer.Deserialize<JsonElement>(outputResult);
var contentTypes = data.GetProperty("content_types").EnumerateArray().ToList();
return contentTypes;
}
catch (Exception ex)
Expand All @@ -336,7 +335,7 @@ public async Task<IList> GetContentTypes(Dictionary<string, object> param = null
}
}

private async Task<JObject> GetLivePreviewData()
private async Task<JsonElement> GetLivePreviewData()
{

Dictionary<String, object> headerAll = new Dictionary<string, object>();
Expand Down Expand Up @@ -368,8 +367,8 @@ private async Task<JObject> GetLivePreviewData()
{
HttpRequestHandler RequestHandler = new HttpRequestHandler(this);
var outputResult = await RequestHandler.ProcessRequest(String.Format("{0}/content_types/{1}/entries/{2}", this.Config.getLivePreviewUrl(this.LivePreviewConfig), this.LivePreviewConfig.ContentTypeUID, this.LivePreviewConfig.EntryUID), headerAll, mainJson, Branch: this.Config.Branch, isLivePreview: true, timeout: this.Config.Timeout, proxy: this.Config.Proxy);
JObject data = JsonConvert.DeserializeObject<JObject>(outputResult.Replace("\r\n", ""), this.SerializerSettings);
return (JObject)data["entry"];
var data = JsonSerializer.Deserialize<JsonElement>(outputResult);
return data.GetProperty("entry");
}
catch (Exception ex)
{
Expand Down Expand Up @@ -784,7 +783,7 @@ private async Task<SyncStack> GetResultAsync(string Init = "false", SyncType Syn
{
HttpRequestHandler requestHandler = new HttpRequestHandler(this);
string js = await requestHandler.ProcessRequest(_SyncUrl, _LocalHeaders, mainJson, Branch: this.Config.Branch, timeout: this.Config.Timeout, proxy: this.Config.Proxy);
SyncStack stackSyncOutput = JsonConvert.DeserializeObject<SyncStack>(js);
SyncStack stackSyncOutput = JsonSerializer.Deserialize<SyncStack>(js);
return stackSyncOutput;
}
catch (Exception ex)
Expand Down
24 changes: 12 additions & 12 deletions Contentstack.Core/Internals/AssetJsonConverter.cs
Original file line number Diff line number Diff line change
@@ -1,27 +1,27 @@
using System;
using Contentstack.Core;
using System.Text.Json;
using System.Text.Json.Serialization;
using Contentstack.Core.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Contentstack.Core.Internals
{
[CSJsonConverter("AssetJsonConverter")]
public class AssetJsonConverter : JsonConverter<Asset>
{
public override Asset ReadJson(JsonReader reader, Type objectType, Asset existingValue, bool hasExistingValue, JsonSerializer serializer)
public override Asset Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
JObject jObject = JObject.Load(reader);
JsonSerializerSettings SerializerSettings = new JsonSerializerSettings();
JsonSerializer Serializer = JsonSerializer.Create(SerializerSettings);
Asset asset = jObject.ToObject<Asset>(Serializer);
asset.ParseObject(jObject);
return asset;
using (JsonDocument document = JsonDocument.ParseValue(ref reader))
{
JsonElement root = document.RootElement;
Asset asset = JsonSerializer.Deserialize<Asset>(root.GetRawText(), options);
asset.ParseObject(root);
return asset;
}
}

public override void WriteJson(JsonWriter writer, Asset value, JsonSerializer serializer)
public override void Write(Utf8JsonWriter writer, Asset value, JsonSerializerOptions options)
{
throw new NotImplementedException();
}
}
}
}
12 changes: 6 additions & 6 deletions Contentstack.Core/Internals/ContentStackError.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
using Newtonsoft.Json;
using System;
using System;
using System.Collections.Generic;
using System.Net;

using System.Text.Json.Serialization;

namespace Contentstack.Core.Internals
{
/// <summary>
Expand Down Expand Up @@ -33,7 +33,7 @@ public class ContentstackException : Exception
/// <summary>
/// This is error message.
/// </summary>
[JsonProperty("error_message")]
[JsonPropertyName("error_message")]
public string ErrorMessage
{
get
Expand All @@ -50,13 +50,13 @@ public string ErrorMessage
/// <summary>
/// This is error code.
/// </summary>
[JsonProperty("error_code")]
[JsonPropertyName("error_code")]
public int ErrorCode { get; set; }

/// <summary>
/// Set of errors in detail.
/// </summary>
[JsonProperty("errors")]
[JsonPropertyName("errors")]
public Dictionary<string, object> Errors { get; set; }

#endregion
Expand Down
6 changes: 1 addition & 5 deletions Contentstack.Core/Internals/ContentstackConvert.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,5 @@
using Newtonsoft.Json;
using System;
using System;
using System.IO;
using System.Net.NetworkInformation;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;

namespace Contentstack.Core.Internals
Expand Down
34 changes: 17 additions & 17 deletions Contentstack.Core/Internals/HttpRequestHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@
using System.Linq;
using System.Net;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Contentstack.Core.Internals
{
Expand Down Expand Up @@ -35,7 +35,7 @@ public async Task<string> ProcessRequest(string Url, Dictionary<string, object>
return value;
}
else if (kvp.Value is Dictionary<string, object>)
value = JsonConvert.SerializeObject(kvp.Value);
value = JsonSerializer.Serialize(kvp.Value);
else
return String.Format("{0}={1}", kvp.Key, kvp.Value);

Expand Down Expand Up @@ -75,7 +75,7 @@ public async Task<string> ProcessRequest(string Url, Dictionary<string, object>
request = await plugin.OnRequest(client, request);
};

var serializedresult = JsonConvert.SerializeObject(BodyJson);
var serializedresult = JsonSerializer.Serialize(BodyJson);
byte[] requestBody = Encoding.UTF8.GetBytes(serializedresult);
StreamReader reader = null;
HttpWebResponse response = null;
Expand Down Expand Up @@ -108,42 +108,42 @@ public async Task<string> ProcessRequest(string Url, Dictionary<string, object>

}

internal void updateLivePreviewContent(JObject response)
internal void updateLivePreviewContent(JsonObject response)
{
if (response.ContainsKey("uid") && response["uid"].ToString() == this.client.LivePreviewConfig.EntryUID)
{
response.Merge(this.client.LivePreviewConfig.PreviewResponse, new JsonMergeSettings()
foreach (var property in this.client.LivePreviewConfig.PreviewResponse.AsObject())
{
MergeArrayHandling = MergeArrayHandling.Replace
});
response[property.Key] = property.Value;
}
}
else
{
foreach (var content in response)
{
if (content.Value.Type == JTokenType.Array)
if (content.Value is JsonArray)
{
updateArray((JArray)response[content.Key]);
updateArray((JsonArray)response[content.Key]);
}
else if (content.Value.Type == JTokenType.Object)
else if (content.Value is JsonObject)
{
updateLivePreviewContent((JObject)response[content.Key]);
updateLivePreviewContent((JsonObject)response[content.Key]);
}
}
}
}

internal void updateArray(JArray array)
internal void updateArray(JsonArray array)
{
for (var i = 0; i < array.Count(); i++)
{
if (array[i].Type == JTokenType.Array)
if (array[i] is JsonArray)
{
updateArray((JArray)array[i]);
updateArray((JsonArray)array[i]);
}
else if (array[i].Type == JTokenType.Object)
else if (array[i] is JsonObject)
{
updateLivePreviewContent((JObject)array[i]);
updateLivePreviewContent((JsonObject)array[i]);
}
}
}
Expand Down
Loading
Loading