繁体   English   中英

决定自定义 Class 动态解析 Json

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM