Der JSON kann entweder in einem Format vorliegen, das SpecificOne oder SpecificTwo unterstützt. Das wissen wir erst zur Laufzeit. Sobald wir es deserialisieren, muss ich die Felder und Werte in Form der Klasse Response extrahieren.
Können wir einen benutzerdefinierten Deserialisierer erstellen, der die Felder und Werte extrahiert?
Code: Select all
var resp = JsonSerializer.Deserialize(json);
Das Ergebnis sollte so aussehen:
Code: Select all
{
"FieldName": "Address",
"FieldValue": "Some Address"
}
Code: Select all
using System.Reflection;
using System.Text.Json;
using System.Text.Json.Serialization;
class Program
{
public static void Main(string[] args)
{
string json = """
{
"Id" : 1,
"Details": {
"$type": "AddressChange",
"Address": "Some Address"
}
}
""";
MyClass obj = JsonSerializer.Deserialize(json);
List fields = [];
var details = obj.Details;
Type type = details.GetType();
foreach (PropertyInfo prop in type.GetProperties())
{
object? value = prop.GetValue(details);
if (value is not null)
{
fields.Add(new Response
{
FieldName = prop.Name,
FieldValue = value.ToString() ?? string.Empty
});
}
}
}
public class MyClass
{
public int Id { get; set; }
public Parent Details { get; set; }
}
[JsonPolymorphic(TypeDiscriminatorPropertyName = "$type")]
[JsonDerivedType(typeof(SpecificOne), "AddressChange")]
[JsonDerivedType(typeof(SpecificTwo), "NameChange")]
public abstract class Parent
{
}
public class SpecificOne : Parent
{
public string Address { get; set; }
}
public class SpecificTwo : Parent
{
public string Name { get; set; }
}
public class Response
{
public string FieldName { get; set; }
public string FieldValue { get; set; }
}
}
Mobile version