Skip to content

Revert "refactor: Updating to system.text.json" #96

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

Merged
merged 1 commit into from
Apr 29, 2025
Merged
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 .github/workflows/jira.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ jobs:
project: ${{ secrets.JIRA_PROJECT }}
issuetype: ${{ secrets.JIRA_ISSUE_TYPE }}
summary: |
Snyk | Vulnerability | ${{ github.event.repository.name }} | ${{ github.event.pull_request.title }}
${{ github.event.pull_request.title }}
description: |
PR: ${{ github.event.pull_request.html_url }}

Expand Down
12 changes: 10 additions & 2 deletions .github/workflows/sca-scan.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,18 @@ jobs:
security-sca:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@master
- name: Checkout repository
uses: actions/checkout@master
- name: Setup .NET Core @ Latest
uses: actions/setup-dotnet@v1
with:
dotnet-version: "7.0.x"
- name: Run Dotnet Restore
run: |
dotnet restore
- name: Run Snyk to check for vulnerabilities
uses: snyk/actions/dotnet@master
env:
SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }}
with:
args: --fail-on=all
args: --file=Contentstack.Core/obj/project.assets.json --fail-on=all
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: 29bb8548d65cdc5800fc939e526797bb3515f528d8082a58a0c9c6215dec1651
checksum: 93c1659f3bc7527956f0fd12db46441297fac3a4366d273bcbb3425d2351300e
- filename: Contentstack.Core/Models/Entry.cs
checksum: 79320b005882981fd7c79fe73832f28284db686927942e46b422ac9e88405023
- filename: Contentstack.Core/ContentstackClient.cs
Expand Down
2 changes: 1 addition & 1 deletion CODEOWNERS
Original file line number Diff line number Diff line change
@@ -1 +1 @@
* @contentstack/security-admin
* @contentstack/security-admin
6 changes: 4 additions & 2 deletions Contentstack.Core/Configuration/LivePreviewConfig.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
using System.Text.Json;
using System;
using System.Collections;
using Newtonsoft.Json.Linq;

namespace Contentstack.Core.Configuration
{
Expand All @@ -11,6 +13,6 @@ public class LivePreviewConfig
internal string LivePreview { get; set; }
internal string ContentTypeUID { get; set; }
internal string EntryUID { get; set; }
internal JsonElement PreviewResponse { get; set; }
internal JObject PreviewResponse { get; set; }
}
}
3 changes: 2 additions & 1 deletion 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>net7.0</TargetFrameworks>
<TargetFrameworks>netstandard2.0;net47;net472;</TargetFrameworks>
<PackageId>contentstack.csharp</PackageId>
<Authors>Contentstack</Authors>
<Description>.NET SDK for the Contentstack Content Delivery API.</Description>
Expand All @@ -28,6 +28,7 @@
<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: 34 additions & 33 deletions Contentstack.Core/ContentstackClient.cs
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
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.Linq;
using System.Net;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using Contentstack.Core.Configuration;
using System.Net;
using System.IO;
using System.Collections;
using Contentstack.Utils;
using Contentstack.Core.Interfaces;
using Contentstack.Core.Internals;
using Contentstack.Core.Models;
using Microsoft.Extensions.Options;

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

#region Internal Variables

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

internal JsonSerializer Serializer => JsonSerializer.Create(SerializerSettings);
internal string _SyncUrl
{
get
Expand Down Expand Up @@ -140,6 +133,10 @@ 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 @@ -212,18 +209,22 @@ internal static ContentstackException GetContentstackError(Exception ex)
using (var reader = new StreamReader(stream))
{
errorMessage = reader.ReadToEnd();
var data = JsonSerializer.Deserialize<JsonElement>(errorMessage);
JObject data = JObject.Parse(errorMessage.Replace("\r\n", ""));

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

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

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

if (exResp is HttpWebResponse response)
var response = exResp as HttpWebResponse;
if (response != null)
statusCode = response.StatusCode;
}
}
Expand Down Expand Up @@ -325,8 +326,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);
var data = JsonSerializer.Deserialize<JsonElement>(outputResult);
var contentTypes = data.GetProperty("content_types").EnumerateArray().ToList();
JObject data = JsonConvert.DeserializeObject<JObject>(outputResult.Replace("\r\n", ""), this.SerializerSettings);
IList contentTypes = (IList)data["content_types"];
return contentTypes;
}
catch (Exception ex)
Expand All @@ -335,7 +336,7 @@ public async Task<IList> GetContentTypes(Dictionary<string, object> param = null
}
}

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

Dictionary<String, object> headerAll = new Dictionary<string, object>();
Expand Down Expand Up @@ -367,8 +368,8 @@ private async Task<JsonElement> 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);
var data = JsonSerializer.Deserialize<JsonElement>(outputResult);
return data.GetProperty("entry");
JObject data = JsonConvert.DeserializeObject<JObject>(outputResult.Replace("\r\n", ""), this.SerializerSettings);
return (JObject)data["entry"];
}
catch (Exception ex)
{
Expand Down Expand Up @@ -785,7 +786,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 = JsonSerializer.Deserialize<SyncStack>(js);
SyncStack stackSyncOutput = JsonConvert.DeserializeObject<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 System.Text.Json;
using System.Text.Json.Serialization;
using Contentstack.Core;
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 Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
public override Asset ReadJson(JsonReader reader, Type objectType, Asset existingValue, bool hasExistingValue, JsonSerializer serializer)
{
using (JsonDocument document = JsonDocument.ParseValue(ref reader))
{
JsonElement root = document.RootElement;
Asset asset = JsonSerializer.Deserialize<Asset>(root.GetRawText(), options);
asset.ParseObject(root);
return asset;
}
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;
}

public override void Write(Utf8JsonWriter writer, Asset value, JsonSerializerOptions options)
public override void WriteJson(JsonWriter writer, Asset value, JsonSerializer serializer)
{
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 System;
using Newtonsoft.Json;
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>
[JsonPropertyName("error_message")]
[JsonProperty("error_message")]
public string ErrorMessage
{
get
Expand All @@ -50,13 +50,13 @@ public string ErrorMessage
/// <summary>
/// This is error code.
/// </summary>
[JsonPropertyName("error_code")]
[JsonProperty("error_code")]
public int ErrorCode { get; set; }

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

#endregion
Expand Down
6 changes: 5 additions & 1 deletion Contentstack.Core/Internals/ContentstackConvert.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
using System;
using Newtonsoft.Json;
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 = JsonSerializer.Serialize(kvp.Value);
value = JsonConvert.SerializeObject(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 = JsonSerializer.Serialize(BodyJson);
var serializedresult = JsonConvert.SerializeObject(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(JsonObject response)
internal void updateLivePreviewContent(JObject response)
{
if (response.ContainsKey("uid") && response["uid"].ToString() == this.client.LivePreviewConfig.EntryUID)
{
foreach (var property in this.client.LivePreviewConfig.PreviewResponse.AsObject())
response.Merge(this.client.LivePreviewConfig.PreviewResponse, new JsonMergeSettings()
{
response[property.Key] = property.Value;
}
MergeArrayHandling = MergeArrayHandling.Replace
});
}
else
{
foreach (var content in response)
{
if (content.Value is JsonArray)
if (content.Value.Type == JTokenType.Array)
{
updateArray((JsonArray)response[content.Key]);
updateArray((JArray)response[content.Key]);
}
else if (content.Value is JsonObject)
else if (content.Value.Type == JTokenType.Object)
{
updateLivePreviewContent((JsonObject)response[content.Key]);
updateLivePreviewContent((JObject)response[content.Key]);
}
}
}
}

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