Скажем, общее имя модели — DataModel, определенное с помощью одного свойства UpdateTime следующим образом:
Код: Выделить всё
using Newtonsoft.Json;
public class DataModel
{
public DateTime UpdateTime { get; set; }
}
Код: Выделить всё
public ArticleContent : DataModel
{
public string Title { get; set; }
public string Content { get; set; }
}
public CommentContent : DataModel
{
public string Comment { get; set; }
public int ArticleId { get; set; }
}
- Создайте перечисление, которое связано с каждым типом (например, ArtileContent, CommentContent):
Код: Выделить всё
public enum ContentType
{
Article = 0,
Comment,
Opinion,
}
- Затем создайте класс-оболочку ApiResponse, который имеет следующие два свойства:
- TypeOfContent (для указания DataModel)
- общее свойство ContentModel
Чтобы реализовать это решение, мне пришлось реорганизовать ответ JSON, включив в него два поля:Код: Выделить всё
public class ApiResponse where T : DataModel { public ContentType TypeOfContent { get; set; } public T ContentModel { get; set; } }При анализе строки JSON мне пришлось сначала десериализовать ее в общую модель данных:Код: Выделить всё
{ "TypeOfContent": 0, "ContentModel": { "Title": "Article 1 Title", "Content": "ABC content" } } Код: Выделить всё
ApiResponse apiResponse = JsonConvert.DeserializeObject(apiJsonResponse);- Проверьте TypeOfContent в apiResponse с помощью блока if-else if, а затем выполните синтаксический анализ для конкретного тип:
Код: Выделить всё
if (apiResponse.TypeOfContent == ContentType.Article) {
ApiResponse articleResponse = JsonConvert.DeserializeObject(apiJsonResponse);
} else if (apiResponse.TypeOfContent == ContentType.Comment) {
///
}
Подробнее здесь: https://stackoverflow.com/questions/793 ... cific-type
Мобильная версия