我们使用外部API,使用对象名称"Data"返回其结果.这个"数据"可以表示两个不同的对象 - 一个是json对象数组的形式,另一个是单个json对象的形式.
我有一个创建的两个独立的c#类代表JSON对象数据和ac#root对象类,用于在使用JsonConvert.DeserializeObject进行转换时捕获JSON对象...如何在C#中正确表示这些对象?请参阅下面的示例结果:
下面是1个API调用的示例
{
success:true,
Data:[{id:1,name:"Paul"},{id:2,name:"neville"},{id:3,name:"jason"}]
}
public class User
{
public int id { get; set; }
public string name { get; set; }
}
public class ApiResponse
{
public bool success { get; set; }
public List<User> Data { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
以下是结果API调用的示例2
{
success:true,
Data:{id:1,classSize:30,minAge:25, maxAge:65}
}
public class AgeClass
{
public int id { get; set; }
public int classSize { get; set; }
public int minAge { get; set; }
public int maxAge { get; set; }
}
public class ApiResponse
{
public bool success { get; set; }
public AgeClass Data { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我将如何构造ApiResponse类以满足返回的通用"数据"对象json字符串 - 以便我可以使用泛型"JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync(),Settings);"
我建议考虑您实际上有 2 种类型的 JSON 响应。您还可以从 ApiResponse 基类继承它们:
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
string json1 = @"{
""success"":true,
""Data"":[{id:1, name:""Paul""},{id:2,name:""neville""},{id:3,name:""jason""}]
}";
string json2 = @"{
""success"":true,
""Data"":{id:1,classSize:30,minAge:25, maxAge:65}
}";
string j = json1; //json2;
JObject jo = JObject.Parse(j);
ApiResponse parsed;
if (jo["Data"].Type == JTokenType.Array)
parsed = jo.ToObject<ApiUsersResponse>();
else
parsed = jo.ToObject<ApiAgeResponse>();
Console.ReadKey();
}
}
class User
{
public int id { get; set; }
public string name { get; set; }
}
class AgeClass
{
public int id { get; set; }
public int classSize { get; set; }
public int minAge { get; set; }
public int maxAge { get; set; }
}
class ApiResponse
{
public bool success { get; set; }
}
class ApiUsersResponse : ApiResponse
{
public List<User> Data { get; set; }
}
class ApiAgeResponse : ApiResponse
{
public AgeClass Data { get; set; }
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
437 次 |
| 最近记录: |