vendredi 12 octobre 2018

Print object with nested properties as string of comma separted key-value pairs

I have a Person class:

public class Person
{
    public string Name { get; set; }
    public string Surname { get; set; }
    public Address Address { get; set; }
}

public class Address
{
    public string Line1 { get; set; }
    public string Line2 { get; set; }
}

As an end result, I would like to print out a Person instance as JSON, but I'd like it to be a huge string of key-value pairs, e.g.:

"Name:John,Surname:Doe,Line1:Infinite Loop,Line2:California"

Notice that in the example above, I got rid of the actual class names (i.e. it prints out Line1 instead of Address.Line1) - i only care about all the name/value pairs.

So the end result would be an array of Persons:

"persons":[
    "Name:John,Surname:Doe,Line1:Infinite Loop 1,Line2:California",            
    "Name:Jane,Surname:Doe,Line1:Infinite Loop 2,Line2:California"
]

As a starting point, I tried using reflection:

void Main()
{
    var persons = new List<Person>();
    persons.Add(new Person
    {
        Name = "John",
        Surname = "Doe",
        Address = new Address
        {
            Line1 = "Infinite Loop",
            Line2 = "California"                
        }
    });

    foreach(var person in persons)
    {
        var properties = new List<string>();
        foreach(var property in person.GetType().GetProperties())
        {
            properties.Add($"{property.Name}:{property.GetValue(person, null)}");
        }
        Console.WriteLine(string.Join(";", properties));
    }
}

But I get the following output in LINQPad:

Name:John;Surname:Doe;Address:UserQuery+Address

I assume Address is not properly iterated upon because it's a nested object within Person. Even so, this doesn't look like the most clean/efficient approach.





Aucun commentaire:

Enregistrer un commentaire