diff --git a/.github/workflows/jira.yml b/.github/workflows/jira.yml index caa4bbd..250abc7 100644 --- a/.github/workflows/jira.yml +++ b/.github/workflows/jira.yml @@ -21,7 +21,7 @@ jobs: project: ${{ secrets.JIRA_PROJECT }} issuetype: ${{ secrets.JIRA_ISSUE_TYPE }} summary: | - ${{ github.event.pull_request.title }} + Snyk | Vulnerability | ${{ github.event.repository.name }} | ${{ github.event.pull_request.title }} description: | PR: ${{ github.event.pull_request.html_url }} diff --git a/.github/workflows/sca-scan.yml b/.github/workflows/sca-scan.yml index decebb1..4fa4560 100644 --- a/.github/workflows/sca-scan.yml +++ b/.github/workflows/sca-scan.yml @@ -6,18 +6,10 @@ jobs: security-sca: runs-on: ubuntu-latest steps: - - 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 + - uses: actions/checkout@master - name: Run Snyk to check for vulnerabilities uses: snyk/actions/dotnet@master env: SNYK_TOKEN: ${{ secrets.SNYK_TOKEN }} with: - args: --file=Contentstack.Core/obj/project.assets.json --fail-on=all + args: --fail-on=all diff --git a/.talismanrc b/.talismanrc index 2fd7ede..5104629 100644 --- a/.talismanrc +++ b/.talismanrc @@ -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 diff --git a/CODEOWNERS b/CODEOWNERS index 0773923..1be7e0d 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -1 +1 @@ -* @contentstack/security-admin \ No newline at end of file +* @contentstack/security-admin diff --git a/Contentstack.Core/Configuration/LivePreviewConfig.cs b/Contentstack.Core/Configuration/LivePreviewConfig.cs index 240db8e..0fbecdf 100644 --- a/Contentstack.Core/Configuration/LivePreviewConfig.cs +++ b/Contentstack.Core/Configuration/LivePreviewConfig.cs @@ -1,6 +1,4 @@ -using System; -using System.Collections; -using Newtonsoft.Json.Linq; +using System.Text.Json; namespace Contentstack.Core.Configuration { @@ -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; } } } diff --git a/Contentstack.Core/Contentstack.Core.csproj b/Contentstack.Core/Contentstack.Core.csproj index 030a3a7..4d4bb79 100644 --- a/Contentstack.Core/Contentstack.Core.csproj +++ b/Contentstack.Core/Contentstack.Core.csproj @@ -1,7 +1,7 @@  - netstandard2.0;net47;net472; + net7.0 contentstack.csharp Contentstack .NET SDK for the Contentstack Content Delivery API. @@ -28,7 +28,6 @@ - diff --git a/Contentstack.Core/ContentstackClient.cs b/Contentstack.Core/ContentstackClient.cs index b86d2f4..e76fe32 100644 --- a/Contentstack.Core/ContentstackClient.cs +++ b/Contentstack.Core/ContentstackClient.cs @@ -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 { @@ -24,7 +23,16 @@ public class ContentstackClient /// /// Gets or sets the settings that should be used for deserialization. /// - 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 @@ -35,7 +43,6 @@ internal string StackApiKey } private ContentstackOptions _options; - internal JsonSerializer Serializer => JsonSerializer.Create(SerializerSettings); internal string _SyncUrl { get @@ -133,10 +140,6 @@ public ContentstackClient(IOptions 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))) { @@ -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(errorMessage); - JToken token = data["error_code"]; - if (token != null) - errorCode = token.Value(); + if (data.TryGetProperty("error_code", out var token)) + errorCode = token.GetInt32(); - token = data["error_message"]; - if (token != null) - errorMessage = token.Value(); + if (data.TryGetProperty("error_message", out token)) + errorMessage = token.GetString(); - token = data["errors"]; - if (token != null) - errors = token.ToObject>(); + if (data.TryGetProperty("errors", out token)) + errors = JsonSerializer.Deserialize>(token.GetRawText()); - var response = exResp as HttpWebResponse; - if (response != null) + if (exResp is HttpWebResponse response) statusCode = response.StatusCode; } } @@ -326,8 +325,8 @@ public async Task GetContentTypes(Dictionary 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(outputResult.Replace("\r\n", ""), this.SerializerSettings); - IList contentTypes = (IList)data["content_types"]; + var data = JsonSerializer.Deserialize(outputResult); + var contentTypes = data.GetProperty("content_types").EnumerateArray().ToList(); return contentTypes; } catch (Exception ex) @@ -336,7 +335,7 @@ public async Task GetContentTypes(Dictionary param = null } } - private async Task GetLivePreviewData() + private async Task GetLivePreviewData() { Dictionary headerAll = new Dictionary(); @@ -368,8 +367,8 @@ private async Task 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(outputResult.Replace("\r\n", ""), this.SerializerSettings); - return (JObject)data["entry"]; + var data = JsonSerializer.Deserialize(outputResult); + return data.GetProperty("entry"); } catch (Exception ex) { @@ -786,7 +785,7 @@ private async Task 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(js); + SyncStack stackSyncOutput = JsonSerializer.Deserialize(js); return stackSyncOutput; } catch (Exception ex) diff --git a/Contentstack.Core/Internals/AssetJsonConverter.cs b/Contentstack.Core/Internals/AssetJsonConverter.cs index 9fc7215..96e581b 100644 --- a/Contentstack.Core/Internals/AssetJsonConverter.cs +++ b/Contentstack.Core/Internals/AssetJsonConverter.cs @@ -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 { - 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(Serializer); - asset.ParseObject(jObject); - return asset; + using (JsonDocument document = JsonDocument.ParseValue(ref reader)) + { + JsonElement root = document.RootElement; + Asset asset = JsonSerializer.Deserialize(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(); } } -} +} \ No newline at end of file diff --git a/Contentstack.Core/Internals/ContentStackError.cs b/Contentstack.Core/Internals/ContentStackError.cs index cb37a80..52f9b56 100644 --- a/Contentstack.Core/Internals/ContentStackError.cs +++ b/Contentstack.Core/Internals/ContentStackError.cs @@ -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 { /// @@ -33,7 +33,7 @@ public class ContentstackException : Exception /// /// This is error message. /// - [JsonProperty("error_message")] + [JsonPropertyName("error_message")] public string ErrorMessage { get @@ -50,13 +50,13 @@ public string ErrorMessage /// /// This is error code. /// - [JsonProperty("error_code")] + [JsonPropertyName("error_code")] public int ErrorCode { get; set; } /// /// Set of errors in detail. /// - [JsonProperty("errors")] + [JsonPropertyName("errors")] public Dictionary Errors { get; set; } #endregion diff --git a/Contentstack.Core/Internals/ContentstackConvert.cs b/Contentstack.Core/Internals/ContentstackConvert.cs index b2d4d74..a35a235 100644 --- a/Contentstack.Core/Internals/ContentstackConvert.cs +++ b/Contentstack.Core/Internals/ContentstackConvert.cs @@ -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 diff --git a/Contentstack.Core/Internals/HttpRequestHandler.cs b/Contentstack.Core/Internals/HttpRequestHandler.cs index 6252f51..e8710f0 100644 --- a/Contentstack.Core/Internals/HttpRequestHandler.cs +++ b/Contentstack.Core/Internals/HttpRequestHandler.cs @@ -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 { @@ -35,7 +35,7 @@ public async Task ProcessRequest(string Url, Dictionary return value; } else if (kvp.Value is Dictionary) - value = JsonConvert.SerializeObject(kvp.Value); + value = JsonSerializer.Serialize(kvp.Value); else return String.Format("{0}={1}", kvp.Key, kvp.Value); @@ -75,7 +75,7 @@ public async Task ProcessRequest(string Url, Dictionary 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; @@ -108,42 +108,42 @@ public async Task ProcessRequest(string Url, Dictionary } - 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]); } } } diff --git a/Contentstack.Core/Internals/JsonSerializerOptionsConverters.cs b/Contentstack.Core/Internals/JsonSerializerOptionsConverters.cs new file mode 100644 index 0000000..834e318 --- /dev/null +++ b/Contentstack.Core/Internals/JsonSerializerOptionsConverters.cs @@ -0,0 +1,68 @@ +using System; +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; + +public class CustomUtcDateTimeConverter : JsonConverter +{ + public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + if (reader.TokenType == JsonTokenType.String) + { + // Parse the string, treating it as UTC if no timezone is specified + if (DateTime.TryParse(reader.GetString(), CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out DateTime dateTime)) + { + return dateTime.Kind == DateTimeKind.Unspecified + ? DateTime.SpecifyKind(dateTime, DateTimeKind.Utc) + : dateTime; + } + } + + return reader.GetDateTime(); + } + + public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options) + { + // Ensure the datetime is in UTC when writing + writer.WriteStringValue(value.Kind == DateTimeKind.Local + ? value.ToUniversalTime() + : value); + } +} + +public class CustomNullableUtcDateTimeConverter : JsonConverter +{ + public override DateTime? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + if (reader.TokenType == JsonTokenType.Null) + return null; + + if (reader.TokenType == JsonTokenType.String) + { + // Parse the string, treating it as UTC if no timezone is specified + if (DateTime.TryParse(reader.GetString(), CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out DateTime dateTime)) + { + return dateTime.Kind == DateTimeKind.Unspecified + ? DateTime.SpecifyKind(dateTime, DateTimeKind.Utc) + : dateTime; + } + } + + return reader.GetDateTime(); + } + + public override void Write(Utf8JsonWriter writer, DateTime? value, JsonSerializerOptions options) + { + if (value.HasValue) + { + // Ensure the datetime is in UTC when writing + writer.WriteStringValue(value.Value.Kind == DateTimeKind.Local + ? value.Value.ToUniversalTime() + : value.Value); + } + else + { + writer.WriteNullValue(); + } + } +} \ No newline at end of file diff --git a/Contentstack.Core/Internals/StackOutput.cs b/Contentstack.Core/Internals/StackOutput.cs index a934059..0b20489 100644 --- a/Contentstack.Core/Internals/StackOutput.cs +++ b/Contentstack.Core/Internals/StackOutput.cs @@ -1,8 +1,5 @@ -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; -using System; +using System; using System.Collections.Generic; -using System.Linq; namespace Contentstack.Core.Internals diff --git a/Contentstack.Core/Models/Asset.cs b/Contentstack.Core/Models/Asset.cs index 05756a2..47355f8 100644 --- a/Contentstack.Core/Models/Asset.cs +++ b/Contentstack.Core/Models/Asset.cs @@ -3,12 +3,13 @@ using System.IO; using System.Linq; using System.Net; +using System.Text.Json; +using System.Text.Json.Nodes; +using System.Text.Json.Serialization; using System.Threading.Tasks; using Contentstack.Core.Configuration; using Contentstack.Core.Internals; using Contentstack.Utils.Interfaces; -using Newtonsoft.Json; -using Newtonsoft.Json.Linq; namespace Contentstack.Core.Models { @@ -98,19 +99,19 @@ public string Url /// /// This is Asset type uid. /// - [JsonProperty(propertyName: "_content_type_uid")] + [JsonPropertyName("_content_type_uid")] public string ContentTypeUid { get; set; } /// /// The size of the file in bytes. /// - [JsonProperty(PropertyName = "file_size")] + [JsonPropertyName("file_size")] public string FileSize { get; set; } /// /// The original name of the file. /// - [JsonProperty(PropertyName = "filename")] + [JsonPropertyName("filename")] public string FileName { get; set; } /// @@ -126,50 +127,50 @@ public string Url /// /// This content_type in asset. /// - [JsonProperty(propertyName: "content_type")] + [JsonPropertyName("content_type")] public string ContentType { get; set; } /// /// This for whether it is asset directory /// - [JsonProperty(propertyName: "is_dir")] + [JsonPropertyName("is_dir")] public Boolean IsDir { get; set; } /// /// Uid of user who updated the file /// - [JsonProperty(PropertyName = "updated_by")] - public string UpdatedBy { get; set; } - + [JsonPropertyName("updated_by")] + public string UpdatedBy { get; set; } + /// /// Uid of user who updated the file /// - [JsonProperty(PropertyName = "created_by")] + [JsonPropertyName("created_by")] public string CreatedBy { get; set; } /// /// The Uid of folder in which the asset is present /// - [JsonProperty(PropertyName = "parent_uid")] + [JsonPropertyName("parent_uid")] public string ParentUid { get; set; } /// /// The Version of Asset /// - [JsonProperty(PropertyName = "_version")] + [JsonPropertyName("_version")] public string Version { get; set; } /// /// Dimension Object of the asset containing Height and width /// - [JsonProperty(PropertyName = "dimension")] + [JsonPropertyName("dimension")] public Dictionary Dimension { get; set; } /// /// Dimension Object of the asset containing Height and width /// - [JsonProperty(PropertyName = "publish_details")] + [JsonPropertyName("publish_details")] public Dictionary PublishDetails { get; set; } #region Internal Constructors @@ -306,9 +307,9 @@ public void RemoveHeader(string key) } - internal void ParseObject(JObject jsonObj) + internal void ParseObject(JsonElement jsonObj) { - this._ObjectAttributes = jsonObj.ToObject>(); + this._ObjectAttributes = JsonSerializer.Deserialize>(jsonObj); } public DateTime GetCreateAt() @@ -419,8 +420,9 @@ public async Task Fetch() { HttpRequestHandler RequestHandler = new HttpRequestHandler(this.StackInstance); var outputResult = await RequestHandler.ProcessRequest(_Url, headers, mainJson, Branch: this.StackInstance.Config.Branch, timeout: this.StackInstance.Config.Timeout, proxy: this.StackInstance.Config.Proxy); - JObject obj = JObject.Parse(ContentstackConvert.ToString(outputResult, "{}")); - return obj.SelectToken("$.asset").ToObject(this.StackInstance.Serializer); + JsonObject obj = JsonNode.Parse(ContentstackConvert.ToString(outputResult, "{}")).AsObject(); + // TODO: the serializer earlier taken was this.StackInstance.Serializer + return JsonSerializer.Deserialize(obj["$.asset"].ToJsonString(), new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); } catch (Exception ex) { @@ -486,21 +488,16 @@ internal static ContentstackException GetContentstackError(Exception ex) using (var reader = new StreamReader(stream)) { errorMessage = reader.ReadToEnd(); - JObject data = JObject.Parse(errorMessage.Replace("\r\n", "")); - //errorCode = ContentstackConvert.ToInt32(data.Property("error_code").Value); - //errorMessage = ContentstackConvert.ToString(data.Property("error_message").Value); + JsonObject data = JsonNode.Parse(errorMessage.Replace("\r\n", "")).AsObject(); - JToken token = data["error_code"]; - if (token != null) - errorCode = token.Value(); + if (data.TryGetPropertyValue("error_code", out JsonNode token)) + errorCode = token.GetValue(); - token = data["error_message"]; - if (token != null) - errorMessage = token.Value(); + if (data.TryGetPropertyValue("error_message", out token)) + errorMessage = token.GetValue(); - token = data["errors"]; - if (token != null) - errors = token.ToObject>(); + if (data.TryGetPropertyValue("errors", out token)) + errors = JsonSerializer.Deserialize>(token.ToJsonString()); var response = exResp as HttpWebResponse; if (response != null) diff --git a/Contentstack.Core/Models/AssetLibrary.cs b/Contentstack.Core/Models/AssetLibrary.cs index 2c7e88d..548a7a4 100644 --- a/Contentstack.Core/Models/AssetLibrary.cs +++ b/Contentstack.Core/Models/AssetLibrary.cs @@ -3,10 +3,11 @@ using System.IO; using System.Linq; using System.Net; +using System.Text.Json; +using System.Text.Json.Nodes; using System.Threading.Tasks; using Contentstack.Core.Configuration; using Contentstack.Core.Internals; -using Newtonsoft.Json.Linq; namespace Contentstack.Core.Models { @@ -86,13 +87,13 @@ public void SortWithKeyAndOrderBy(String key, OrderBy order) /// JObject jObject = await assetLibrary.Count(); /// /// - public async Task Count() + public async Task Count() { UrlQueries.Add("count", "true"); return await Exec(); } - public AssetLibrary Query(JObject QueryObject) + public AssetLibrary Query(JsonObject QueryObject) { try { @@ -435,9 +436,10 @@ public AssetLibrary RemoveHeader(string key) /// public async Task> FetchAll() { - JObject json = await Exec(); - var assets = json.SelectToken("$.assets").ToObject>(this.Stack.Serializer); - var collection = json.ToObject>(this.Stack.Serializer); + JsonObject json = await Exec(); + // TODO: the serializer earlier taken was this.StackInstance.Serializer + var assets = JsonSerializer.Deserialize>(json["assets"].ToJsonString(), new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); + var collection = JsonSerializer.Deserialize>(json.ToJsonString(), new JsonSerializerOptions { PropertyNameCaseInsensitive = true }); foreach (var entry in assets) { if (entry.GetType() == typeof(Asset)) @@ -449,7 +451,7 @@ public async Task> FetchAll() return collection; } - private async Task Exec() + private async Task Exec() { Dictionary headers = GetHeader(_Headers); @@ -474,7 +476,7 @@ private async Task Exec() { HttpRequestHandler RequestHandler = new HttpRequestHandler(this.Stack); var outputResult = await RequestHandler.ProcessRequest(_Url, headers, mainJson, Branch: this.Stack.Config.Branch, timeout: this.Stack.Config.Timeout, proxy: this.Stack.Config.Proxy); - return JObject.Parse(ContentstackConvert.ToString(outputResult, "{}")); + return JsonNode.Parse(ContentstackConvert.ToString(outputResult, "{}")).AsObject(); } catch (Exception ex) @@ -541,23 +543,22 @@ internal static ContentstackException GetContentstackError(Exception ex) using (var reader = new StreamReader(stream)) { errorMessage = reader.ReadToEnd(); - JObject data = JObject.Parse(errorMessage.Replace("\r\n", "")); + JsonObject data = JsonNode.Parse(errorMessage.Replace("\r\n", "")).AsObject(); - JToken token = data["error_code"]; - if (token != null) - errorCode = token.Value(); + if (data.TryGetPropertyValue("error_code", out JsonNode token)) + errorCode = token.GetValue(); - token = data["error_message"]; - if (token != null) - errorMessage = token.Value(); + if (data.TryGetPropertyValue("error_message", out token)) + errorMessage = token.GetValue(); - token = data["errors"]; - if (token != null) - errors = token.ToObject>(); + if (data.TryGetPropertyValue("errors", out token)) + errors = JsonSerializer.Deserialize>(token.ToJsonString()); var response = exResp as HttpWebResponse; if (response != null) + { statusCode = response.StatusCode; + } } } catch diff --git a/Contentstack.Core/Models/ContentType.cs b/Contentstack.Core/Models/ContentType.cs index 837d15a..5642950 100644 --- a/Contentstack.Core/Models/ContentType.cs +++ b/Contentstack.Core/Models/ContentType.cs @@ -1,13 +1,13 @@ using System; using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Text.Json; +using System.Text.Json.Nodes; +using System.Threading.Tasks; using Contentstack.Core.Configuration; using Contentstack.Core.Internals; -using System.Threading.Tasks; -using System.Net; -using Newtonsoft.Json.Linq; -using System.Linq; -using System.IO; -using Newtonsoft.Json; namespace Contentstack.Core.Models { @@ -82,23 +82,22 @@ internal static ContentstackException GetContentstackError(Exception ex) using (var reader = new StreamReader(stream)) { errorMessage = reader.ReadToEnd(); - JObject data = JObject.Parse(errorMessage.Replace("\r\n", "")); + JsonObject data = JsonNode.Parse(errorMessage.Replace("\r\n", "")).AsObject(); - JToken token = data["error_code"]; - if (token != null) - errorCode = token.Value(); + if (data.TryGetPropertyValue("error_code", out JsonNode token)) + errorCode = token.GetValue(); - token = data["error_message"]; - if (token != null) - errorMessage = token.Value(); + if (data.TryGetPropertyValue("error_message", out token)) + errorMessage = token.GetValue(); - token = data["errors"]; - if (token != null) - errors = token.ToObject>(); + if (data.TryGetPropertyValue("errors", out token)) + errors = JsonSerializer.Deserialize>(token.ToJsonString()); var response = exResp as HttpWebResponse; if (response != null) + { statusCode = response.StatusCode; + } } } catch @@ -139,7 +138,7 @@ internal void SetStackInstance(ContentstackClient stack) /// /// is dictionary of additional parameter /// The Content-Type Schema Object. - public async Task Fetch(Dictionary param = null) + public async Task Fetch(Dictionary param = null) { Dictionary headers = GetHeader(_Headers); Dictionary headerAll = new Dictionary(); @@ -170,8 +169,8 @@ public async Task Fetch(Dictionary param = null) { HttpRequestHandler RequestHandler = new HttpRequestHandler(this.StackInstance); var outputResult = await RequestHandler.ProcessRequest(_Url, headers, mainJson, Branch: this.StackInstance.Config.Branch, timeout: this.StackInstance.Config.Timeout, proxy: this.StackInstance.Config.Proxy); - JObject data = JsonConvert.DeserializeObject(outputResult.Replace("\r\n", ""), this.StackInstance.SerializerSettings); - JObject contentTypes = (Newtonsoft.Json.Linq.JObject)data["content_type"]; + JsonObject data = JsonNode.Parse(outputResult.Replace("\r\n", "")).AsObject(); + JsonObject contentTypes = data["content_type"].AsObject(); return contentTypes; } catch (Exception ex) diff --git a/Contentstack.Core/Models/ContentstackCollection.cs b/Contentstack.Core/Models/ContentstackCollection.cs old mode 100755 new mode 100644 index 0edd7c6..458f5d4 --- a/Contentstack.Core/Models/ContentstackCollection.cs +++ b/Contentstack.Core/Models/ContentstackCollection.cs @@ -1,14 +1,10 @@ -using Newtonsoft.Json; -using System; -using System.Collections; +using System.Collections; using System.Collections.Generic; -using System.Text; namespace Contentstack.Core.Models { - [JsonObject] - public class ContentstackCollection : IEnumerable - { + public class ContentstackCollection : IEnumerable + { /// /// The number of items skipped in this resultset. ///