c#-从对象数组中检索值
我正在从我的c#应用程序调用一个外部API,它以json数组的形式返回数据,响应体如下所示c#-从对象数组中检索值,c#,arrays,dictionary,object,C#,Arrays,Dictionary,Object,我正在从我的c#应用程序调用一个外部API,它以json数组的形式返回数据,响应体如下所示 { "result": [ { "name": "Tom", "id": "EM123" }, { "name": "John", "id": "EM154"
{
"result": [
{
"name": "Tom",
"id": "EM123"
},
{
"name": "John",
"id": "EM154"
}
]
}
在我的c#应用程序中,我只想检索第一个元素的Id,对于上面的响应体,它将是EM123
上面是一个示例代码,我想从我的对象数组obj中检索“EM123”我的第一个建议是使用。如果您按照提供的方式向它提供JSON响应,它将为您提供适当的C#对象定义。在本例中,定义如下所示:
public partial class ApiResponse
{
[JsonProperty("result")]
public Result[] Result { get; set; }
}
public partial class Result
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("id")]
public string Id { get; set; }
}
}
添加这两个类后,您将能够执行以下操作:
var apiResponse = JsonConvert.DeserializeObject<ApiResponse>(reponse);
Console.WriteLine("This is what I need: " + apiResponse.Result.First().Id);
var-apiResponse=JsonConvert.DeserializeObject(response);
WriteLine(“这就是我需要的:+apiResponse.Result.First().Id);
希望这有帮助。将json作为一个具体类的数组,然后使用
ToDictionary
上述方法与Newtonsoft库一起使用。var response=Newtonsoft.Json.JsonConvert.DeserializeObject(result)您是对的。这是我的错误,我使用了jsonresponse而不是JsonConvert