【问题标题】:How to break up StreamReader responseStream into segments to build array/objects如何将 StreamReader responseStream 分解为段以构建数组/对象
【发布时间】:2021-10-12 09:45:38
【问题描述】:

我想要做的是将 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\"}]"

【问题讨论】:

    标签: c# json.net


    【解决方案1】:

    字符串看起来像一个有效的 JSON 数组表示,应该可以毫无问题地进行解析。你可以使用JArray.Parse来解析它(https://www.newtonsoft.com/json/help/html/ParseJsonArray.htm

    您还可以查看JsonConvert.DeserializeObject&lt;T&gt; 以获得更多类型安全的解析方式。查看详情:How do I deserialize a JSON array using Newtonsoft.Jsonhttps://www.newtonsoft.com/json/help/html/DeserializeCollection.htm

    【讨论】:

      猜你喜欢
      • 2021-03-15
      • 1970-01-01
      • 1970-01-01
      • 2023-01-25
      • 2017-06-11
      • 1970-01-01
      • 1970-01-01
      • 2018-03-07
      • 2016-11-09
      相关资源
      最近更新 更多