我要做的是将从webRequest返回的字符串分解为段,以便我可以将它们转换为我的客户对象。该字符串包含5个客户的数据,但它返回为1个大字符串。JObject.Parse()处理单个项目,但不像当前接收字符串那样处理多个项目。
public IEnumerable<Customer> GetByPage(int page)
{
try
{
WebRequest request = WebRequest.Create($"http://localhost:5002/api/customer/GetByPage?page={page}");
using (WebResponse response = request.GetResponse())
using (StreamReader stream = new StreamReader(response.GetResponseStream()))
{
incomingStream = stream.ReadToEnd();
//breaks here
jsonObj = JObject.Parse(incomingStream);
//Use the returned jsonObj to build a customer object
customer.Id = Int32.Parse((string)jsonObj.GetValue("id"));
customer.TitleId = Int32.Parse((string)jsonObj.GetValue("id"));
customer.FirstName = (string)jsonObj.GetValue("firstName");
}
}
catch (Exception)
{
throw;
}
return customers;
}
这是它给我的字符串(为了简单,我删除了很多)"[{"id":1005,"titleId":6,"languageId":1,"termsId":2,"statusId":1,"profileId":1,"firstName":"K"},{"id":1006,"titleId":5,"languageId":2,"termsId":1,"statusId":1,"profileId":1,"firstName":"P"}]"
该字符串看起来像一个有效的JSON数组表示,应该可以毫无问题地解析。您可以使用JArray.Parse
来解析它(https://www.newtonsoft.com/json/help/html/ParseJsonArray.htm)
您还可以检查JsonConvert.DeserializeObject<T>
以获得更类型安全的解析方式。查看详细信息:如何使用Newtonsoft反序列化JSON数组。Json或https://www.newtonsoft.com/json/help/html/DeserializeCollection.htm