[英]Decide Custom Class Dynamically to parse Json
我需要將 Json 解析為 class,許多屬性保持不變,但有一個 object 是基於已傳遞的 JSON 類型的動態屬性,例如,如果它是 Customer.json,我需要一起解析 CustomerAttributes使用 BaseResponse,如果它是 Order.json,我需要 OrderAttributes 和 BaseResponse。 我事先知道那里有什么類型的 Json。
這是我的代碼。
public abstract class BaseResponse
{
public int Id {get;set;}
public int Name {get;set;}
public CommonResponse metadata { get; set; }
}
public class CommonResponse
{
public string apiVersion { get; set; }
public Pagination pagination { get; set; }
// I need CustomerAttributes here if I am parsing Customer.Json and
// OrderAttributes here if I am parsing Order.Json
}
public class Pagination
{
public int totalPages { get; set; }
public int number { get; set; }
public int size { get; set; }
}
public class CustomerAttributes
{
public int Age { get; set;}
public string Address { get; set;}
}
public class OrderAttributes
{
public int Amount { get; set;}
public DateTime startDate { get; set;}
public DateTime endDate { get; set;}
}
我無法弄清楚我的 CommonResponse class 中應該包含什么來解析這兩個屬性。
有多種方法可以處理此類情況。 以下是我發現自己最常使用的那些。
如果調用解析器的代碼可以知道它需要哪種類型,則可以使該屬性通用:
public class CommonResponse<TAttributes>
{
public string apiVersion { get; set; }
public Pagination pagination { get; set; }
public TAttributes attributes { get; set; }
}
另一方面,如果您直到稍后才知道它可能是哪種類型,您可以只使用 JObject (或您正在使用的 JSON 解析庫的等效類型),並在您知道什么的時候反序列化它輸入你期望的:
public class CommonResponse
{
public string apiVersion { get; set; }
public Pagination pagination { get; set; }
public JObject attributes { get; set; }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.