Created
November 30, 2024 11:28
-
-
Save dazfuller/afc8769f9ea21bc5c925eacef8dba44b to your computer and use it in GitHub Desktop.
Filtering out multiple string values as null values when deserializing a JSON string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Text.Json; | |
using System.Text.Json.Nodes; | |
using System.Text.Json.Serialization; | |
namespace JsonConvertExample; | |
internal static class Program | |
{ | |
private static void Main() | |
{ | |
const string inputJson = """{ "prop1":"val", "prop2":10, "prop3":"", "prop4":["val", "-", "val2"], "prop5":{ "sub1":"val", "sub2":"N/A" } }"""; | |
var options = new JsonSerializerOptions | |
{ | |
WriteIndented = false, | |
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull | |
}; | |
options.Converters.Add(new CustomJsonConverter()); | |
var document = JsonSerializer.Deserialize<JsonNode>(inputJson, options); | |
Console.WriteLine(JsonSerializer.Serialize(document, options)); | |
} | |
} | |
public class CustomJsonConverter : JsonConverter<JsonNode> | |
{ | |
public override JsonNode? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) | |
{ | |
var node = JsonNode.Parse(ref reader); | |
return FilterJsonNode(node); | |
} | |
private static bool IsNullValue(string value) | |
{ | |
return value.ToUpper() is "" or "-" or "N/A"; | |
} | |
private static JsonNode? FilterJsonNode(JsonNode? node) | |
{ | |
switch (node) | |
{ | |
case JsonObject jsonObject: | |
{ | |
foreach (var (key, value) in jsonObject.ToList()) | |
{ | |
if (value is JsonValue jsonValue) | |
{ | |
if (jsonValue.TryGetValue(out string? stringValue) | |
&& IsNullValue(stringValue)) | |
{ | |
jsonObject.Remove(key); | |
} | |
} | |
else | |
{ | |
var filteredValue = FilterJsonNode(value); | |
if (filteredValue is not null) | |
{ | |
jsonObject[key] = filteredValue; | |
} | |
else | |
{ | |
jsonObject.Remove(key); | |
} | |
} | |
} | |
break; | |
} | |
case JsonArray jsonArray: | |
{ | |
for (var i = 0; i < jsonArray.Count; i++) | |
{ | |
var value = jsonArray[i]; | |
if (value is JsonValue jsonValue | |
&& jsonValue.TryGetValue(out string? stringValue) | |
&& IsNullValue(stringValue)) | |
{ | |
jsonArray.RemoveAt(i); | |
i--; | |
} | |
else | |
{ | |
var filteredValue = FilterJsonNode(value); | |
if (filteredValue is not null) | |
{ | |
jsonArray[i] = filteredValue.DeepClone(); | |
} | |
else | |
{ | |
jsonArray.RemoveAt(i); | |
i--; | |
} | |
} | |
} | |
break; | |
} | |
} | |
return node; | |
} | |
public override void Write(Utf8JsonWriter writer, JsonNode value, JsonSerializerOptions options) | |
{ | |
value.WriteTo(writer); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment