Friday, October 12, 2018

Parse the response from a RESTlet in C#

To parse the response of a request to a restlet, create a class to represent the record object returned by the restlet and use the following code snippet as guide:


//sample class
public class Customer
{
public int id { get; set; }
public string companyname { get; set; }
//add additional members as needed
}


Code snippet:


//get the response
WebResponse response = request.GetResponse();


//Create a stream reader to read through the response
StreamReader streamReader = new StreamReader(response.GetResponseStream());


//set the output to a string
string output = streamReader.ReadToEnd();


//Create a serializer to parse the JSON string
JavaScriptSerializer js = new JavaScriptSerializer();


//Create an instance of the Customer object and set its values from the parsed response
Customer rec = js.Deserialize<Customer>(output);


NOTE: The names of the Class' members should match the names of the members of the JSON object returned by the restlet.

No comments:

Post a Comment