jeudi 10 juin 2021

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.





Aucun commentaire:

Enregistrer un commentaire