简体   繁体   中英

Trying to deserialize Json in c#

I am attempting to deserialize JSON in C# in a WCF web service and repackage it as a list. I am using JObject.Parse in Json.NET. Below is the code that I am using to call the web service, get the JSON and put it into a list.

String url = URL to a web service;
HttpWebRequest WebReqOpenPermits = (HttpWebRequest)WebRequest.Create(url);
WebReqOpenPermits.ContentType = "application/json; charset=utf-8";
WebReqOpenPermits.Method = "GET";
HttpWebResponse WebRespOpenPermits = (HttpWebResponse)WebReqOpenPermits.GetResponse();

Stream jsonStream = WebRespOpenPermits.GetResponseStream();
List<routeOpenPermits> permitsList = new List<routeOpenPermits>();
using (StreamReader reader = new StreamReader(jsonStream))
{
   string line;
   routeOpenPermits routeValues = new routeOpenPermits();
   while ((line = reader.ReadLine()) != null)
   {
       JObject results = JObject.Parse(line);
       foreach (var result in results["GetOpenPermitsByIdResult"])
                {
                  routeValues.oAddress = (string)result["oAddress"];
                  routeValues.oDateIssued = (string)result["oDateIssued"];
                  routeValues.oPermit = (string)result["oPermit"];
                  permitsList.Add(routeValues);
                }
            }
        }

This code adds the correct amount of records to the list but only the data for the last record in the JSON string is added to the list. For example, if the JSON data contains 5 records, all are added to the list but the data in the list comes only from the fifth and last record in the JSON string. The data from the fifth record is repeated five times in the list.

What I am doing wrong? Is there a better way because I am open to finding a new method. I have searched for quite a while but have not been able to find a solution. Thank you for any help, examples, guidance or advice that can be sent my way. I am thoroughly frustrated with deserializing JSON.

You should move the line:

routeOpenPermits routeValues = new routeOpenPermits();

into the inside of your foreach loop

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM