|
| 1 | +namespace Microsoft.Graph.PowerShell.JsonUtilities |
| 2 | +{ |
| 3 | + using Newtonsoft.Json.Linq; |
| 4 | + using System.Linq; |
| 5 | + using static Microsoft.Graph.PowerShell.Runtime.Extensions; |
| 6 | + |
| 7 | + public static class JsonExtensions |
| 8 | + { |
| 9 | + /// <summary> |
| 10 | + /// Removes JSON properties that have a value of "defaultnull" and converts properties with values of "null" or empty strings ("") to actual JSON null values. |
| 11 | + /// </summary> |
| 12 | + /// <param name="jsonObject">The JObject to process and clean.</param> |
| 13 | + /// <returns> |
| 14 | + /// A JSON string representation of the cleaned JObject with "defaultnull" properties removed and "null" or empty string values converted to JSON null. |
| 15 | + /// </returns> |
| 16 | + /// <example> |
| 17 | + /// JObject json = JObject.Parse(@"{""name"": ""John"", ""email"": ""defaultnull"", ""address"": ""null""}"); |
| 18 | + /// string cleanedJson = json.RemoveDefaultNullProperties(); |
| 19 | + /// Console.WriteLine(cleanedJson); |
| 20 | + /// // Output: { "name": "John", "address": null } |
| 21 | + /// </example> |
| 22 | + public static string RemoveDefaultNullProperties(this JObject jsonObject) |
| 23 | + { |
| 24 | + try |
| 25 | + { |
| 26 | + foreach (var property in jsonObject.Properties().ToList()) |
| 27 | + { |
| 28 | + if (property.Value.Type == JTokenType.Object) |
| 29 | + { |
| 30 | + RemoveDefaultNullProperties((JObject)property.Value); |
| 31 | + } |
| 32 | + else if (property.Value.Type == JTokenType.Array) |
| 33 | + { |
| 34 | + foreach (var item in property.Value) |
| 35 | + { |
| 36 | + if (item.Type == JTokenType.Object) |
| 37 | + { |
| 38 | + RemoveDefaultNullProperties((JObject)item); |
| 39 | + } |
| 40 | + } |
| 41 | + } |
| 42 | + else if (property.Value.Type == JTokenType.String && property.Value.ToString() == "defaultnull") |
| 43 | + { |
| 44 | + property.Remove(); |
| 45 | + } |
| 46 | + else if (property.Value.Type == JTokenType.String && (property.Value.ToString() == "null" || property.Value.ToString() == "")) |
| 47 | + { |
| 48 | + property.Value = JValue.CreateNull(); |
| 49 | + } |
| 50 | + } |
| 51 | + } |
| 52 | + catch (System.Exception) |
| 53 | + { |
| 54 | + return jsonObject.ToString(); // Return the original string if parsing fails |
| 55 | + } |
| 56 | + return jsonObject.ToString(); |
| 57 | + } |
| 58 | + public static string ReplaceAndRemoveSlashes(this string body) |
| 59 | + { |
| 60 | + return body.Replace("/", "").Replace("\\", "").Replace("rn", "").Replace("\"{", "{").Replace("}\"", "}"); |
| 61 | + } |
| 62 | + } |
| 63 | +} |
0 commit comments