How to get the daily trend from Twitter? - c#

I would like to ask if anyone know how to extract out the "name" and "query" and maybe store it in a arraylist.
Source file: https://api.twitter.com/1/trends/daily.json

You can use JObject , something like: -
string response = requestData("https://api.twitter.com/1/trends/daily.json");
JObject jsonResponse = new JObject();
var name = string.Empty;
var query = string.Empty;
try
{
jsonResponse = JObject.Parse(response);
name = (string)jsonResponse["name"];
query = (string)jsonRespone["query"];
}
catch
{
return "";
}
public string requestData(string url)
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
StreamReader sr = new StreamReader(resp.GetResponseStream());
string results = sr.ReadToEnd();
sr.Close();
return results;
}

Based on this question: Parse JSON in C#
Make a class that represents the JSON you're extracting, and extract the class from the JSON using the code in the JSONHelper class from the linked question:
public class JSONHelper
{
public static T Deserialise<T>(string json)
{
T obj = Activator.CreateInstance<T>();
MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
DataContractJsonSerializer serialiser = new DataContractJsonSerializer(obj.GetType());
ms.Close();
return obj;
}
}

Related

Get value of dynamic objects in ASP.Net Core

I need to read a value from HTTP response. Here is an example of the response in which I'm trying to fetch (description) value:
{
"result":{
"code":"200.300.404",
"description":"successful"
},
"buildNumber":"1f9#2021-12-23 09:56:49 +0000",
"timestamp":"2021-12-25 17:22:35+0000",
"ndc":"8976eaedf8da"
}
Here is my code
Dictionary<string, dynamic> responseData;
string data = "entityId=8a8294174d0595bb014d05d82e5b01d2";
string url = "https://test.oppwa.com/v1/checkouts/" + CheckoutId + "/payment?" + data;
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Method = "GET";
request.Headers["Authorization"] = "Bearer xxxx";
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
// var s = new JavaScriptSerializer();
responseData = JsonSerializer.Deserialize<Dictionary<string, dynamic>>(reader.ReadToEnd());
reader.Close();
dataStream.Close();
}
// If responseDate.Description=success then enroll user and register the payment
var res = responseData["result"];
// I'm trying to do this but not working
var res = responseData["result"]["description"];
return responseData;
Any help is appreciated
Thanks
You can use JToken or JObject of Newtonsoft.Json.Linq.
For example, if your response format like as below:
{
"result":{
"code":"200.300.404",
"description":"successful"
},
"buildNumber":"1f9#2021-12-23 09:56:49 +0000",
"timestamp":"2021-12-25 17:22:35+0000",
"ndc":"8976eaedf8da"
}
You can use below code for this purpose:
...
string webResponseAsString = reader.ReadToEnd();
dynamic dynamicResult = JToken.Parse(webResponseAsString);
string description = dynamicResult.result.description
For more details, you can visit this links:
Using JSON.NET for dynamic JSON parsing
Querying JSON with dynamic
What is better to use when parsing dynamic JSON data: JToken or c# built in dynamic type
try this
StreamReader reader = new StreamReader(dataStream);
var json = reader.ReadToEnd();
...
var jsonObject=JObject.Parse(json);
var result=jsonObject["result"];
var description = jsonObject["result"]["description"];
// or
var description =result["description"];
description value
successful
responseData["result"].description
Will get you the JValue of "successful".
Although there are some other issues. Deserialize needs an instance of JsonSerializer, it is not a static method. Here is a full example without using a Dictionary.
var response = #"
{
""result"":{
""code"":""200.300.404"",
""description"":""successful""
},
""buildNumber"":""1f9#2021-12-23 09:56:49 +0000"",
""timestamp"":""2021-12-25 17:22:35+0000"",
""ndc"":""8976eaedf8da""
}
";
var responseData = new JsonSerializer()
.Deserialize<dynamic>(
new JsonTextReader(new StringReader(response)));
responseData.result.description; //successful

C# Change DateTime in String / Json

I download a json string from a website including a DateTime.
Using this code:
using (HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse())
{
using (Stream responseStream = httpWebResponse.GetResponseStream())
{
using (StreamReader streamReader = new StreamReader(responseStream))
{
value = streamReader.ReadToEnd();
}
}
}
authResponse = JsonConvert.DeserializeObject<Class1.Response>(value);
The Json Class looks like this:
public Response()
{
this.key = ""
this.valid_until = "";
this.xyz = "";
}
The String looks like this:
{
"key":"1424152",
"time_date":"2021-09-19 20:35:17",
"xyz":"Working"
}
Now before I Deserialize it I want to change the Date Time (add 2 days to it) in that string.
How would I approach that?

Use a stream directly to a parsing instead of saving a file

I mean, this is piece of my code:
// Create the web request (posts/1)
HttpWebRequest request = WebRequest.Create("https://jsonplaceholder.typicode.com/posts/1") as HttpWebRequest;
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
{
string myString = reader.ReadToEnd();
System.IO.File.WriteAllText(#"C:\Users\admin\Documents\Visual Studio 2015\Projects\WriteText.json", myString);
}
// JSON deserialize from a file
String JSONstring = File.ReadAllText(#"C:\Users\admin\Documents\Visual Studio 2015\Projects\WriteText.json");
// List<PARSE> pList = JsonConvert.DeserializeObject<List<PARSE>>(JSONstring);
PARSE pList = JsonConvert.DeserializeObject<PARSE>(JSONstring);
How can I do this thing without saving the stream and again loading it to a string. I want use my stream directly to a String 'JSONstring' and then parse it.
Your code contains solution
// Create the web request (posts/1)
HttpWebRequest request = WebRequest.Create("https://jsonplaceholder.typicode.com/posts/1") as HttpWebRequest;
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
{
//string myString = reader.ReadToEnd();
//System.IO.File.WriteAllText(#"C:\Users\admin\Documents\Visual Studio 2015\Projects\WriteText.json", myString);
}
// JSON deserialize from a file
// String JSONstring = File.ReadAllText(#"C:\Users\admin\Documents\Visual Studio 2015\Projects\WriteText.json");
// List<PARSE> pList = JsonConvert.DeserializeObject<List<PARSE>>(JSONstring);
PARSE pList = JsonConvert.DeserializeObject<PARSE>(reader.ReadToEnd());
reader.close();
Here's an example of how to parse an HTTP stream into a Json (with no error handling). Play with it and let us know if you run into anything specific. In this code. API_Json is the class with the deserialized classes, and I am deserializing API_Json.RootObject:
public async Task<API_Json.RootObject> walMart_Lookup(string url)
{
lookupIsWorking = true;
HttpClientHandler handler = new HttpClientHandler()
{
AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
};
using (HttpClient http = new HttpClient(handler))
{
http.DefaultRequestHeaders.AcceptEncoding.Add(new System.Net.Http.Headers.StringWithQualityHeaderValue("gzip"));
http.Timeout = TimeSpan.FromMilliseconds(Timeout.Infinite);
url = String.Format(url);
using (var response = await http.GetAsync(url, HttpCompletionOption.ResponseHeadersRead))
{
Console.WriteLine(response);
var serializer = new JsonSerializer();
using (StreamReader sr = new StreamReader(await response.Content.ReadAsStreamAsync()))
{
using (var jsonTextReader = new JsonTextReader(sr))
{
var root = serializer.Deserialize<API_Json.RootObject>(jsonTextReader);
lookupIsWorking = false;
return root;
}
}
//var obj = (API_Json_Special_Feeds.RootObject)serializer.Deserialize(sr, typeof(API_Json_Special_Feeds.RootObject));
//return obj;
}
}
}

How to return data in json format its returns string

I have following code but its return data in string type.. how to return data in json format.
[HttpGet]
public string Save(BookingInformation BookingJson)
{
SuccessResponse msg = new SuccessResponse();
msg.FleetBookingId = objMaster.Current.Id.ToString();
msg.Success = true;
msg.Message = "Booking saved successfully";
var obj = serializer.Serialize(msg).Trim('"');
return obj;
}
Calling Method
public async void getsave(BookingInformation BookingJson)
{
var baseAddress = new Uri("http://mycar.com");
string url = "/api/Jobs/SaveBooking";
using (var httpClient = new HttpClient { BaseAddress = baseAddress })
{
var Jsonlines = JsonConvert.SerializeObject(BookingJson);
//httpClient.DefaultRequestHeaders.TryAddWithoutValidation("accept-charset", "utf-8");
//httpClient.DefaultRequestHeaders.TryAddWithoutValidation("authorization", "Basic *sample_token*");
using (var content = new StringContent(Jsonlines, System.Text.Encoding.Default, "application/json"))
{
using (var response = await httpClient.PostAsync(url, content))
{
object responseData = await response.Content.ReadAsStringAsync();
}
}
}
}
Result is : how to return only json. I want return data in json format
"{\"FleetBookingId\":\"36572\",\"Success\":true,\"Message\":\"Booking saved successfully\"}"
i want like this :
{"FleetBookingId":"36572","Success":true,"Message":"Booking saved successfully"}
Don't return a string from your API method, but a SuccessResponse and let the API's serializer do its work:
[HttpGet]
public SuccessResponse Save(BookingInformation BookingJson)
{
SuccessResponse msg = new SuccessResponse();
msg.FleetBookingId = objMaster.Current.Id.ToString();
msg.Success = true;
msg.Message = "Booking saved successfully";
return msg;
}
Return A Json Result from Controller
public ActionResult GetSuggestionFirst()
{
var search = Request.Params["term"].Trim();
var itemList = (from items in db.TblProductSuggestionFirsts where items.Name.StartsWith(search) select new { label = items.Name, value = items.Name }).Take(50).ToList();
return Json(itemList, JsonRequestBehavior.AllowGet);
}
This return json object (Json look like string, just parse it in Javascript)
I got the answer thanks :)
var content = new JavaScriptSerializer().Serialize(msg);
JToken json = JObject.Parse(content);

Send XML String as Response

I am getting my Request from a third party application(different domain) to my ASP application. I am handling the request and doing the business part in my application and as a acknowledgement I need to send XML string as Response to the same Page which POSTED the request to my Application. I was successful in retrieving the input from Request using the following code
NameValueCollection postPageCollection = Request.Form;
foreach (string name in postPageCollection.AllKeys)
{
... = postPageCollection[name]);
}
But i am not sure how to send back the response along with XML String to the site(different domain)?
EDIT: How to get the URL from where the POST happened.
You can get the url that come from Request.ServerVariables["HTTP_REFERER"]
For the XML, here are 2 functions that I use
public static string ObjectToXML(Type type, object obby)
{
XmlSerializer ser = new XmlSerializer(type);
using (System.IO.MemoryStream stm = new System.IO.MemoryStream())
{
//serialize to a memory stream
ser.Serialize(stm, obby);
//reset to beginning so we can read it.
stm.Position = 0;
//Convert a string.
using (System.IO.StreamReader stmReader = new System.IO.StreamReader(stm))
{
string xmlData = stmReader.ReadToEnd();
return xmlData;
}
}
}
public static object XmlToObject(Type type, string xml)
{
object oOut = null;
//hydrate based on private string var
if (xml != null && xml.Length > 0)
{
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(type);
using (System.IO.StringReader sReader = new System.IO.StringReader(xml))
{
oOut = serializer.Deserialize(sReader);
sReader.Close();
}
}
return oOut;
}
And here is an example how I use it
[Serializable]
public class MyClassThatKeepTheData
{
public int EnaTest;
}
MyClassThatKeepTheData cTheObject = new MyClassThatKeepTheData();
ObjectToXML(typeof(MyClassThatKeepTheData), cTheObject)
Cant you just use the following code:
Request.UrlReferrer.ToString();

Categories

Resources