C# Serialize a specific property as JSON by using Reflection?

I'm a new guy on the way to learn reflection. My effort is to build a serialization for a specific property in a class, for example:

public class People
{
    public Name Name { get; set; }
    public int Age { get; set; }
    public Address Address { get; set; }
}

public class Name
{
    public string First { get; set; }
    public string Last { get; set; }
}

public class Address
{
    public City City { get; set; }
    public string Street { get; set; }
}

public class City
{
    public string Country { get; set; }
    public string ZipCode { get; set; }
}

Usage:

var manObj = new People
{
    Name = new Name
    {
        First = "Viet",
        Last = "Vo"
    },
    Address = new Address
    {
        City = new City
        {
            Name = "New York",
            ZipCode = "12345"
        },
        Street = "123 Street"
    },
    Age = 20
};

I would like to have a method to get a specific property and serialize it as JSON string :

string firstNameJson = SerializeSpecificProperty(manObj, "Name.First");
string cityZipCodeJson = SerializeSpecificProperty(manObj, "Address.City.ZipCode");

Output as JSON string format:

// first name
{
    Name: {
        First: "Viet"
    }
}

// zip code
{
    Address: {
        City: {
            ZipCode: "12345"
        }
    }
}

I can loop through the class properties, but still can't find the best way to archive that. Thanks.



Read more here: https://stackoverflow.com/questions/67930799/c-sharp-serialize-a-specific-property-as-json-by-using-reflection

Content Attribution

This content was originally published by Hoang Viet at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: