Home > Mobile >  How to break up StreamReader responseStream into segments to build array/objects
How to break up StreamReader responseStream into segments to build array/objects

Time:10-12

What I am trying to do is break down the string that gets returned from a webRequest into segments so I can convert them into my customer object. The string contains data of 5 customers but it returns as 1 large string. JObject.Parse() works on a single item but not for multiple as how the string is currently received.

 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;
        }

This is this string it gives me (I removed a lot of it for simplicity) "[{\"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\"}]"

CodePudding user response:

The string looks like a valid JSON array representation and should be parsed without any issues. You can use JArray.Parse to parse it (https://www.newtonsoft.com/json/help/html/ParseJsonArray.htm)

You can also check the JsonConvert.DeserializeObject<T> for more type-safe way of parsing. See details: How do I deserialize a JSON array using Newtonsoft.Json or https://www.newtonsoft.com/json/help/html/DeserializeCollection.htm

  • Related