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; } }
}
Related
Currently, I am using a [WebMethod] to call an API and get the response as a JSON string.
public string GetFloodData()
{ ...
WebRequest requestObj = WebRequest.Create(url);
requestObj.Method = "GET";
requestObj.ContentType = "application/json";
responseObj = (HttpWebResponse)requestObj.GetResponse();
using (Stream stream = responseObj.GetResponseStream())
{
StreamReader sr = new StreamReader(stream);
strresult = sr.ReadToEnd();
sr.Close();
}
return strresult;
...
}
When I call GetFloodData(), I get the following response in the browser:
<string xmlns="http://tempuri.org/">
{"ListEvents":
[{"EventID":1,"EventName":"Debby2000","State":"PR","EventType":"Tropical or
Extratropical","Days":5,"LSTStart":"\/Date(9666432000000000)\/",
"LSTEnd":"\/Dat e(967075200000-0000)\/"}, {...}....]}
At this point (before I parse it as a formal JSON Object), I just want to eliminate the stuff I don't want ("Days","LSTStart", and "LSTEnd") and keep what I want. How would I limit what attributes are returned in my response?
You can de-serialise it with a class, and in that class, you can write only the variables you do want to keep. Although, keep the structure of the Json and the class as same. Variables can be missing, but the structure should be the same
ok, so I am trying to use JSON.net to purse the JSON string of google maps API to an object:
string url = #"https://maps.googleapis.com/maps/api/directions/json?origin=75+9th+Ave+New+York,+NY&destination=MetLife+Stadium+1+MetLife+Stadium+Dr+East+Rutherford,+NJ+07073&key=YOUR_API_KEY";
WebRequest request = WebRequest.Create(url);
WebResponse response = request.GetResponse();
Stream data = response.GetResponseStream();
StreamReader reader = new StreamReader(data);
string responseFromServer = reader.ReadToEnd();
response.Close();
var result = JsonConvert.DeserializeObject<T>(responseFromServer);
^
|
here
and I need to replace the T with the object that contains all the JSON fields example:
class ex
{
int[] arr;
string str;
(....)
}
however, the JSON string that returned from google maps API is very long and contains many fields, and as I'm pretty new to JSON, I will probably get this wrong. I wonder if there is a way to auto-generate a class to contain all these properties (maybe anonymous types, somehow?) or if someone did this class before me and open-sourced it?
thank you in advance!
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.
I'm newbie to using the dynamic keyword in C#. It seems simple enough, but I can't seem to use it effectively.
I see this example from Facebook:
var client = new FacebookClient();
dynamic me = client.Get("totten");
string firstname = me.first_name;
it works fine, but if you look at me in a debugger, then you can see that client.Get() returns simple JSON. The same it's said in Facebook documentation:
The result of this request is a dynamic object containing various
properties such as first_name, last_name, user name, etc. You can see
the values of this request by browsing to
http://graph.facebook.com/totten in your web browser. The JSON result
is shown below.
I want to do the same dodge with returned JSON from Foursquare:
private static string GetReturnedUrlFromHttp(string url)
{
HttpWebRequest webRequest = WebRequest.Create(url) as HttpWebRequest;
webRequest.Timeout = 10000;
webRequest.Method = "GET";
WebResponse response = webRequest.GetResponse();
string responseStr = String.Empty;
using (var stream = response.GetResponseStream())
{
var r = new StreamReader(stream);
responseStr = r.ReadToEnd();
}
return responseStr;
}
public static void FillDataFromFoursquareUsingDynamic()
{
string foursquare_url_detail = "https://api.foursquare.com/v2/venues/4b80718df964a520e57230e3?locale=en&client_id=XXX&client_secret=YYY&v=10102013";
dynamic responseStr = GetReturnedUrlFromHttp(foursquare_url_detail);
var response = responseStr.response;
}
I got the following error:
'string' does not contain a definition for 'response'
Why am I getting this error and is it possible to 'parse' any JSON string like in Facebook?
FacebookClient.Get doesn't really return the JSON string. Instead it parses the string into a dynamic object with properties matching the names of the values in the JSON string.
Using dynamic doesn't magically turn a string into an object with the properties defined in the string. Instead, you need to first parse the string with the help of a JSON library like JSON.NET.
I have two servers. One is a private server and I don't want users to have direct access to it, and the other one is the server that public does have access to.
I can access my private server by URL like: http://xxx.xx.xxx.xxx/
What i want to do is create some kind of "proxy", only to work with my private server. My idea is to go to: http://www.domain.com/server/path/here/something
This page should show me the content of http://xxx.xx.xxx.xxx/path/here/something
I have this working, but the only way I could make it work was to return the content as a string, and then the browser would interpret the HTML.
This works fine for pages that return HTML content, but it doesn't work (of course) if I want to access a .gif or any kind of file directly.
Here's the code I currently have:
public string Index(string url)
{
string uri = "http://xxx.xx.xxx.xxx/" + url;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader responseStream = new StreamReader(response.GetResponseStream());
string resultado = responseStream.ReadToEnd();
return resultado;
}
How can I change my code so that it works for any file ?
You can check the response content type and do what you need based on that.
You'll need to change your action to return ActionResult instead of string.
if(response.ContentType.Equals("text/html"))
{
//show html stuff
return Content(resultado);
}
else if(response.ContentType.Contains("image/"))
{
var ms = new MemoryStream();
responseStream.BaseStream.CopyTo(ms);
var imageBytes = ms.ToArray();
return File(imageBytes, response.ContentType);
}
you have to write a system which reads your html or images from resultado and do something according to that PLUS you need to control your Url as well.