Parsing json response from httpwebresponse into listView data binding windows - c#

I am making a http post as follows
public async Task<string> HttppostJson()
{
// Create a request using a URL that can receive a post.
HttpWebRequest request = HttpWebRequest.Create("URL") as HttpWebRequest;
// Set the Method property of the request to POST.
request.Method = "POST";
string post = "postData";
byte[] byteArray = Encoding.UTF8.GetBytes(post.ToString());
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
//Write data into a stream
using (var stream = await Task.Factory.FromAsync<Stream>(request.BeginGetRequestStream, request.EndGetRequestStream, null))
{
stream.Write(byteArray, 0, byteArray.Length);
}
// Pick up the response:
using (var response = (HttpWebResponse)(await Task<WebResponse>.Factory.FromAsync(request.BeginGetResponse, request.EndGetResponse, null)))
{
StreamReader reader = new StreamReader(response.GetResponseStream());
result = reader.ReadToEnd();
}
return result;
}
This gives me a JSON string as output. A small part of it is as follows
{
"id":20,
"title":"Testing after phase 2 is shifted to server",
"from":"Administrator",
"sendername":"ABX",
"day":"Tuesday",
"dateofMonth":"20th",
"month":"May",
"year":2014,
"date":"Tuesday, 20th May, 2014",
"content":"Ready. Set. Go"
}
There are 19 more such blocks refering to each "id". I want to deserialize the objects and populate them in a list view , only the "title" and "from" from all 20 notices should be seen in the listView. More id's will be added later so I want to make the listView dynamic which should include the new added id's and corresponding "title" and "from". So the listview should look like this
Title= "title"_corresponding_to_id
subtitle= "from"_correspondin_to_id
Title= "title"_corresponding_to_id
subtitle= "from"_correspondin_to_id
Title= "title"_corresponding_to_id
subtitle= "from"_correspondin_to_id
..
..
..
I am new to Windows app development. SO needed a little help.

You can make Movie class.
Then you can use newtonsoft's Json.NET library and use JObject class.
You just save json response into a string and then get values from JObject and add it to list.
string json = someJsonText
JObject response = JObject.Parse(json);
List<Movie> list = new List<Movie>();
Movie first = new Movie();
first.Title = response.GetValue("title");
list.Add(first);
And do that in foreach or for sentence to get, create and save all the movies.

Related

Passing a custom object to a REST endpoint with C#

I have a rest endpoint that accepts a single custom object parameter containing two properties.
Let's call the param InfoParam
public class InfoParam
{
public long LongVar { get; set; }
public string StringVar { get; set; }
}
My code I have is as follows:
infoParam.LongVar = 12345678;
infoParam.StringVar = "abc"
var myRequest = (HttpWebRequest)WebRequest.Create(url);
myRequest.Method = "POST";
var content = string.Empty;
using (var theResponse = (HttpWebResponse)MyRequest.GetResponse())
{
using (var stream = theResponse.GetResponseStream())
{
using (var sr = new StreamReader(stream))
{
content = sr.ReadToEnd();
}
}
}
So I have the InfoParam variable, with the two values, but I can't figure out where to pass it in to the REST endpoint.
You need to turn the object into a stream of bytes that can be added to the Request stream - which will in turn be sent as the HTTP POST body. The format of these bytes needs to match what the server expects. REST endpoints usually expect these bytes to resemble JSON.
// assuming you have added Newtonsoft.JSON package and added the correct using statements
using (StreamWriter writer = new StreamWriter(myRequest.GetRequestStream()) {
string json = JsonConvert.SerializeObject(infoParam);
writer.WriteLine(json);
writer.Flush();
}
You'll probably want to set various other request parameters, like the Content-Type header.
You have to write it int the `Content (and set content-type). Check out How to: Send data by using the WebRequest class
The recommendation is to use System.Net.Http.HttpClient instead.
Please note that you should know what content the server expects ('application/x-www-form-urlencoded`, json, etc.)
The following snippet is from POST JSON data over HTTP
// Construct the HttpClient and Uri. This endpoint is for test purposes only.
HttpClient httpClient = new HttpClient();
Uri uri = new Uri("https://www.contoso.com/post");
// Construct the JSON to post.
HttpStringContent content = new HttpStringContent(
"{ \"firstName\": \"Eliot\" }",
UnicodeEncoding.Utf8,
"application/json");
// Post the JSON and wait for a response.
HttpResponseMessage httpResponseMessage = await httpClient.PostAsync(
uri,
content);
// Make sure the post succeeded, and write out the response.
httpResponseMessage.EnsureSuccessStatusCode();
var httpResponseBody = await httpResponseMessage.Content.ReadAsStringAsync();
Debug.WriteLine(httpResponseBody);
In your case the content would be something like this
HttpStringContent content = new HttpStringContent(
JsonConvert.SerializeObject(infoParam), // using Json.Net;
UnicodeEncoding.Utf8,
"application/json");

Convert html to json in c#

I have a c# post which returns me html. My post is checking for an organization name and return the list of organizations with that name. My problem is that the post returns the html for whole page and i want only the list of organizations. I think that i should convert to json, or there is other possibility?
Post method:
WebRequest request = WebRequest.Create("http://www.mfinante.ro/numeCod.html");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
string postData = "judet=40&name=ORACLE&submit=Vizualizare";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/x-www-form-urlencoded";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
WebResponse response = request.GetResponse();
// Display the status.
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
The best way to parse an HTML into JSON is
Parse your HTML using HTML Agility Pack.
Depending on what is in your HTML you can create a class in c# and create an object of it OR you can create a list of objects if HTML content is repetitive.
Class MyItem
{
int employeeId = 0;
string employeeName = String.Empty;
}
List<MyItem> list = new List<MyItem>();
JavaScriptSerializer js = new JavaScriptSerializer();
js.Serialize(list);
Depending on the endpoint, you might have luck adding an Accept header to the request, asking for JSON.
I do not what properties that might be set on a WebRequest, but it might be something like
request.Accept = "application/json";
In that way, the request will ask the server to return the result in a JSON format, which might be more usable for you.
If it fails, then you'll have to extract the content from the HTML, constructing an object and then serialise that object into JSON.
I will tell why your question can cause confusion. Consider example of html:
<html>
<body>
<p> example of paragraph </p>
</body>
</html>
Example of json:
{"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]}
json is something, on which html is generated or initial fundament. So when you say you want to convert html to json it's really confusing, because it is impossible to figure out according to which rules you want to make this conversion. Or which tags from html should be ignored/added while creating json.
There is no direct way to convert HTML to JSON. Make a tool!
However, the easiest way I found was to copy/paste the HTML directly from a browser, into Excel, with some manipulation to form a "table" structure.
Next use an Office Script to convert from Excel to JSON.
I created a function to convert the json from HTML to json thanks to the other answer.
public string convertHtmlToJson(string finalHtml, string title, bool status)
{
Wpjson jsonObject = new Wpjson();
jsonObject.Title = title;
jsonObject.Content = finalHtml;
jsonObject.Status = status;
return new JavaScriptSerializer().Serialize(jsonObject);
}
In my class file I created I called it Wpjson and inside I put below:
public class Wpjson
{
string title = string.Empty;
string content = string.Empty;
bool status = false;
public string Title
{ get { return title; } set { title = value; } }
public string Content
{ get { return content; } set { content = value; } }
public bool Status
{ get { return status; } set { status = value; } }
}

Json data to object

Below is my responseFromServer,
{"version":3,"status":"ok","response":{"data":[{"address":"1908 Bull Temple Road","category_ids":[29],"category_labels":[["Community and Government","Education","Colleges and Universities"]],"country":"in","email":"principal#bmsce.ac.in","factual_id":"0c8c762c-52df-48d0-9add-1e6ef3f4df0d","fax":"080 2661 4357","hours":{"monday":[["7:00","15:00"]],"tuesday":[["7:00","14:00"]],"wednesday":[["7:00","13:00"]],"thursday":[["7:00","13:00"]],"friday":[["6:00","14:00"]],"saturday":[["7:00","14:00"]],"sunday":[["10:00","13:00"]]},"hours_display":"Mon 7:00-15:00; Tue 7:00-14:00; Wed-Thu 7:00-13:00; Fri 6:00-14:00; Sat 7:00-14:00; Sun 10:00-13:00","latitude":12.94172,"locality":"Bangalore","longitude":77.565889,"name":"BMS College of Engineering","postcode":"560019","region":"Karnataka","tel":"080 2662 2130","website":"http://www.bmsce.ac.in"},{"address":"R V Vidyanikethan Post, Mysore Road","category_ids":[29],"category_labels":[["Community and Government","Education","Colleges and Universities"]],"country":"in","email":"principal#rvce.ac.in","factual_id":"0389cc9b-0368-4ad7-8259-0c6021cd18d0","fax":"080 2860 0337","latitude":12.923694,"locality":"Bangalore","longitude":77.499105,"name":"R V College Of Engineering","postcode":"560059","region":"Karnataka","tel":"080 2860 1700","website":"http://www.rvce.ac.in"},"included_rows":1,"total_row_count":2}}
i am getting from the below code
WebRequest request = WebRequest.Create("RequestURL");
// If required by the server, set the credentials.
request.Credentials = CredentialCache.DefaultCredentials;
// Get the response.
WebResponse response = request.GetResponse();
// Display the status.
Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
Stream dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
Used:
dynamic json = JsonConvert.DeserializeObject(responseFromServer);
var data = json.response;
foreach (var album in data)
{
var address = album.address;
}
I can't deserialize the response. I want to get the data from the above Json. Any help would be appreciated. Thank you
Your json.response is not Enumerable. The property data in json.response is, you should use
var data = json.response.data as JArray

Receiving Json in HttpPost - ASP.net

I've set up a page to do an HTTP Post with a Json serialized generic list, to a different page in ASP.net. When it goes to the new page though, I can't seem to find the body of the HTTP Post.
This is the method for the post:
public static void SendHttpPost(string json)
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://localhost:57102/Post.aspx");
httpWebRequest.ContentType = "text/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}
}
Although this is the first time I've done this, I presumed you would be able to access the Json using Request.Form or similar, but Request.Form is empty. I've had a good look at the VS degugger and can't see it anywhere in the Request object, but the content length is 68000 bytes, so I'm sure it's in there somewhere!
Can anyone point me in the right direction please? Many thanks
You can retrieve the Request Body using Request.InputStream as shown here : gist.github.com/leggetter/769688 !

Can HttpWebRequest Be Used To Populate a Model?

I am wondering if HttpWebRequest can be used to fill a MVC model? I am trying to build a MVC 4 application where I take data from a college course listing page and massage it in a few different ways in my View. The examples that I have been seeing around have all taken a response stream and returned a string or have not been formatted for MVC (using console.write). Also, as far as I understand, the data as its being returned isn't in a JSON or XML format. Here is my controller so far...
public ActionResult Index()
{
string postData = "semester=20143Fall+2013+++++++++++++++++++++++++++++++&courseid=&subject=IT++INFORMATION+TECHNOLOGY&college=&campus=1%2C2%2C3%2C4%2C5%2C6%2C7%2C9%2CA%2CB%2CC%2CI%2CL%2CM%2CN%2CP%2CQ%2CR%2CS%2CT%2CW%2CU%2CV%2CX%2CZ&courselevel=&coursenum=&startTime=0600&endTime=2359&days=ALL&All=All+Sections";
byte[] dataArray = Encoding.UTF8.GetBytes (postData);
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create("http://www3.mnsu.edu/courses/selectform.asp");
myRequest.Method = "POST";
myRequest.ContentType = "application/x-www-form-urlencoded";
myRequest.ContentLength = dataArray.Length;
using (WebResponse response = myRequest.GetResponse())
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
//insert into a model? Maybe?
}
}
return View();
}
If HttbWebRequest can't be used, is there a way that would work? Or am I completely heading in the wrong direction?
You can using HttpWebRequest and WebResponse to get stream from your college course's web site. Then use HtmlAgilityPack to parse scrap in the stream and insert your desired value into model

Categories

Resources