【发布时间】:2018-10-30 13:22:12
【问题描述】:
您好,我想从 Web 服务返回的 JSON 对象中读取 ID:
[{"id":11,"username":"test5"}]
代码:
HttpResponseMessage response = null;
using (response = httpClient.PostAsync(url, content).Result)
{
try
{
response.EnsureSuccessStatusCode(); //200 Ok
string responJsonText = response.Content.ReadAsStringAsync().Result;
JObject res = JObject.Parse(responJsonText);
//if ((int)res["id"][0] > 0)
// {
var uid = (int)res["id"][0];
if (uid > 0)
{
return uid;
}
else
{ return 0; }
// }
// else
//{ return 0; }
}
如何使用 C# 从 Json Response 中读取 Id 和用户名?
我收到以下消息的异常:
从 JsonReader 读取 JObject 时出错。当前 JsonReader 项不是对象:StartArray。路径
【问题讨论】:
-
您的代码面临哪些具体问题/错误?我想知道异步操作是否有问题 - 您可能需要等待它,否则在您移至下一行并尝试读取响应之前它不会准备好。
res["id"][0]也没有多大意义,因为 id 不是数组。
标签: c# .net json asp.net-web-api