如何将JSON反序列化为泛型对象,并根据JSON中的数据结构得到合适的类型?
How to deserialize a JSON to generic objects and get the appropriate type based on the data structure in the JSON?
我想得到这些JSON返回的通用数据对象:
{
"data": {
"playlist": {
"id": "37682",
"title": "my_playlist",
"count": 12,
"duration": 9705,
...
}
}
}
但我也可以得到这个:
{
"data": {
"album": {
"id": "372",
"cover": ""
"title": "Longing",
"duration": 7705,
"count": 12,
"artist": "the artist"
...
}
}
}
我的通用 class 应该得到服务器返回的 data
对象:
public class GenericResponse<T> : IGenericResponse
{
[JsonProperty("data")]
public T Data { get; set; }
object IResponse.Data => Data;
}
我要反序列化的对象之一 GenericResponse<T>
:
[JsonObject("playlist")]
public class PlaylistObject
{
[JsonProperty("id")]
public string Id;
[JsonProperty("title")]
public string Title;
[JsonProperty("duration")]
public int Duration;
[JsonProperty("count")]
public int Count;
}
请求和反序列化:
GenericResponse result = await myEndpoint
.WithOAuthBearerToken(myBearer)
.Request()
.PostAsync(content)
.ReceiveJson<GenericResponse<T>>();
服务器发送的数据在那里,但是当我将其反序列化为 GenericResponse<T>
时 result
变量始终为空,其中 T
是 PlaylistObject
或AlbumObject
您的 class 结构不太正确,您缺少围绕播放列表对象的包装器 class,它具有 playlist
属性。例如:
public class PlaylistWrapper
{
public PlaylistObject Playlist { get; set; }
}
现在您应该可以直接反序列化为 GenericResponse<PlaylistWrapper>
我想得到这些JSON返回的通用数据对象:
{
"data": {
"playlist": {
"id": "37682",
"title": "my_playlist",
"count": 12,
"duration": 9705,
...
}
}
}
但我也可以得到这个:
{
"data": {
"album": {
"id": "372",
"cover": ""
"title": "Longing",
"duration": 7705,
"count": 12,
"artist": "the artist"
...
}
}
}
我的通用 class 应该得到服务器返回的 data
对象:
public class GenericResponse<T> : IGenericResponse
{
[JsonProperty("data")]
public T Data { get; set; }
object IResponse.Data => Data;
}
我要反序列化的对象之一 GenericResponse<T>
:
[JsonObject("playlist")]
public class PlaylistObject
{
[JsonProperty("id")]
public string Id;
[JsonProperty("title")]
public string Title;
[JsonProperty("duration")]
public int Duration;
[JsonProperty("count")]
public int Count;
}
请求和反序列化:
GenericResponse result = await myEndpoint
.WithOAuthBearerToken(myBearer)
.Request()
.PostAsync(content)
.ReceiveJson<GenericResponse<T>>();
服务器发送的数据在那里,但是当我将其反序列化为 GenericResponse<T>
时 result
变量始终为空,其中 T
是 PlaylistObject
或AlbumObject
您的 class 结构不太正确,您缺少围绕播放列表对象的包装器 class,它具有 playlist
属性。例如:
public class PlaylistWrapper
{
public PlaylistObject Playlist { get; set; }
}
现在您应该可以直接反序列化为 GenericResponse<PlaylistWrapper>