C#&.NET/.NET 6应用程序如何将一个C#的Class类的源文件动态(运行时)转换成JSON字符串呢?
1.39K 次浏览
如题,在C#&.NET/.NET 6应用程序中,如何将一个C#的Class类的源文件动态(运行时)转换成JSON字符串呢?
比如有一个包含C#源代码的Customer.txt文件,代码如下:
public class Customer
{
public Customer()
{
Addresses = new List<Address>
{
new()
};
}
public int Id { get; set; }
public string Name { get; set; }
public List<Address> Addresses { get; set; }
}
public class Address
{
public Address()
{
Contact = new Contact();
}
public string Province { get; set; }
public string City { get; set; }
public Contact Contact { get; set; }
}
public class Contact
{
public int Id { get; set; }
public string Phone { get; set; }
}
如何将以上定义的C#类转换成对应的JSON对象呢?
期望的结果是:
{
"id": 0,
"name": null,
"addresses": [
{
"province": null,
"city": null,
"contact": {
"id": 0,
"phone": null
}
}
]
}