I need to obtain several pieces of information from a tweet using the json twitter API.
The only source provided is a tweet link.
This solution requires no twitter authentication and only 1 library json.net (available in Nuget Package Manager)
So far:
The program is able to do a httprequest on the Twitter json API.
I can see a response in the stream
But I am not able to deserialize the json response into the class.
Where:
Place a breakpoint in line and You will see that json_data contains json.
MyTweet = JsonConvert.DeserializeObject(json_data);
using System;
using System.IO;
using System.Net;
using Newtonsoft.Json;
namespace parsejson
{
class Program
{
static void Main(string[] args)
{
try
{
Tweet MyTweet = new Tweet();
string url;
url = "https://api.twitter.com/1/statuses/oembed.json?url=https://twitter.com/katyperry/status/657469411700244480";
var json_data = string.Empty;
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
req.Method = WebRequestMethods.Http.Get;
req.Accept = "application/json";
req.ContentType = "applicaton/json;charset=utf-8";
WebResponse resp = req.GetResponse();
Stream stream = resp.GetResponseStream();
StreamReader sr = new StreamReader(stream);
json_data = sr.ReadToEnd();
MyTweet = JsonConvert.DeserializeObject<Tweet>(json_data);
var stext = MyTweet.text;
Console.ReadLine();
}
catch (Exception)
{
throw;
}
}
public class Tweet
{
public string created_at { get; set; }
public long id { get; set; }
public string id_str { get; set; }
public string text { get; set; }
public string source { get; set; }
}
}
}
Related
this is my current code:
public string Get(int id)
{
HttpRequestCachePolicy policy = new HttpRequestCachePolicy(HttpRequestCacheLevel.Default);
HttpWebRequest.DefaultCachePolicy = policy;
HttpRequestCachePolicy noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("some URl that returns a json");
request.Method = WebRequestMethods.Http.Get;
request.Accept = "application/json";
request.ContentType = "application/json; charset=utf-8";
request.MaximumAutomaticRedirections = 4;
request.MaximumResponseHeadersLength = 4;
request.Credentials = CredentialCache.DefaultCredentials;
request.CachePolicy = noCachePolicy;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
return // RESPONSE AS JSON???;
}
public class Persons
{
public string index { get; set; }
public string thing { get; set; }
public string name { get; set; }
public string title { get; set; }
}
I want to return the response as multidimensional json..
How can i do that?
It should look like this:
{"data":{"Person1":{"id":1,"thing":"thingOne","name":"personOneName","title":"personOneTitle"},"Person2":{"id":2,"thing":"thingTwo","name":"personTwoName","title":"personTwoTitle"}}
Be sure to add the directive below to your class
using Newtonsoft.Json;
This code will turn your response into an object.
Stream newStream = response .GetResponseStream();
StreamReader sr = new StreamReader(newStream);
var result = sr.ReadToEnd();
//this will turn your response into a c# object of RootObject Type
//only do this is you're sure it will Deserialize into a RootObject type.
var convertResponseToObj= JsonConvert.DeserializeObject<RootObject>(result);
//if you want to see what's being returned by your endpoint
//without turning it into a RootObject type then remove <RootObject> see line below.
//doing this may help you Deserialize the response correctly.
//var convertResponseToObj= JsonConvert.DeserializeObject(result);
public class Persons
{
public string index { get; set; }
public string thing { get; set; }
public string name { get; set; }
public string title { get; set; }
}
public class RootObject
{
public List<Person> data {get; set;}
}
If you want to do some manipulations to that c# object and then turn it into JSON you can can do this:
string myJson = JsonConvert.SerializeObject(someCSharpObj); //this will turn your c# object into json
I am working on a requirement where I need to create multiple issues in one go by Using the REST API. However, I start with uploading a single issue because I am new in API integration. I write few lines of code in c#. Here is my code:
static void Main(string[] args)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
JiraCreateIssueRequest jcir = new JiraCreateIssueRequest();
//////////////////////////////////////////////////////////////////
string sUsername = "aaa#xyz.com";
string sPassword = "TestPassword";
string uri = #"https://domain.atlassian.net/rest/api/2/issue";
Uri address = new Uri(uri);
HttpWebRequest request;
//HttpWebResponse response = null;
StreamReader sr;
string sData = null;
string returnXML = string.Empty;
if (address == null) { throw new ArgumentNullException("address"); }
//jcir.project.ID = 100;
//jcir.Summary = "This issue is created by JIRA REST Api";
//jcir.Description = "This issue is created by JIRA REST Api";
//jcir.IssueType.ID = 1;
sData = #"{""fields"":{""project"":{""key"": ""SITT""},""summary"": ""REST API Uploading"",""description"":""Creating an issue via REST API"",""issuetype"": {""name"": ""Test""}}}";
//sData = jcir.ToString();
try
{
// Create and initialize the web request
request = WebRequest.Create(address) as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/json";
// Add the Authorization header to the web request
request.Credentials = new NetworkCredential(sUsername, sPassword);
//Write Data
if (sData != null)
{
byte[] byteData = UTF8Encoding.UTF8.GetBytes(sData);
// Set the content length in the request headers
request.ContentLength = byteData.Length;
// Write data
using (Stream postStream = request.GetRequestStream())
{
postStream.Write(byteData, 0, byteData.Length);
}
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
string str = reader.ReadToEnd();
}
}
}
catch (WebException wex)
{
// This exception will be raised if the server didn't return 200 - OK
// Try to retrieve more information about the error
if (wex.Response != null)
{
using (HttpWebResponse errorResponse = (HttpWebResponse)wex.Response)
{
try
{
string sError = string.Format("The server returned '{0}' with the status code {1} ({2:d}).",
errorResponse.StatusDescription, errorResponse.StatusCode,
errorResponse.StatusCode);
sr = new StreamReader(errorResponse.GetResponseStream(), Encoding.UTF8);
returnXML = sr.ReadToEnd();
}
finally
{
if (errorResponse != null) errorResponse.Close();
}
}
}
else
{
throw new Exception(wex.Message);
}
}
}
public class JiraCreateIssueRequest
{
protected JavaScriptSerializer jss = new JavaScriptSerializer();
public JiraProject project = new JiraProject();
public string Summary { get; set; }
public string Description { get; set; }
public JiraIssueType IssueType = new JiraIssueType();
public override string ToString()
{
return jss.Serialize(this);
}
}
public class JiraCreateIssueResponse
{
}
public class JiraProject
{
public int ID { get; set; }
//public string Key { get; set; }
}
public class JiraIssueType
{
public int ID { get; set; }
//public string Name { get; set; }
}
But when I am running the above code, I am getting the '400' error. I googled it and found that this usually this error comes when the URL or the Username/Password are incorrect. I cross checked both the things however its correct.
May I know why this error is coming or what will be the resolution of the problem?
Your password is not your login password, it's an API token that you get from here:
https://id.atlassian.com/manage/api-tokens
Generate a token, then use that as your password.
The thing is, code is compilig without problems, but im expecting deserialized Json file in console instead of this:
And my code is:
using System;
using System.IO;
using System.Net;
using Newtonsoft.Json;
using System.Web.Script.Serialization;
using System.Collections.Generic;
namespace GetRequest
{
class PARSE
{
public int userID { get; set; }
public int id { get; set; }
public string title { get; set; }
public string body { get; set; }
public override string ToString()
{
return string.Format("UserID: {0} \nid: {1} \ntitle: {2} \nbody {3}", userID, id, title, body);
}
}
class Program
{
static void Main(string[] args)
{
// Create the web request
HttpWebRequest request = WebRequest.Create("https://jsonplaceholder.typicode.com/posts") 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> p = JsonConvert.DeserializeObject<List<PARSE>>(JSONstring);
Console.WriteLine(p);
Console.ReadLine();
}
}
}
}
I will be thankful if someone can help me a little :)
You're printing out the list, use a loop to iterate through your list of objects and then print them out.
Try this:
using System;
using System.IO;
using System.Net;
using Newtonsoft.Json;
using System.Web.Script.Serialization;
using System.Collections.Generic;
namespace GetRequest
{
class PARSE
{
public int userID { get; set; }
public int id { get; set; }
public string title { get; set; }
public string body { get; set; }
public override string ToString()
{
return string.Format("UserID: {0} \nid: {1} \ntitle: {2} \nbody {3}", userID, id, title, body);
}
}
class Program
{
static void Main(string[] args)
{
// Create the web request
HttpWebRequest request = WebRequest.Create("https://jsonplaceholder.typicode.com/posts") 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);
foreach(PARSE p in pList) {
Console.WriteLine(p);
Console.ReadLine();
}
}
}
}
}
I have this json value that I want to convert to a List
[{
"id_cuenta": 1,
"nombre": "Mercedes Luj\u00e1n",
"apellido": "Llano",
"ci": 123,
"telefono": 123456789,
"dispositivo_id": "355790037549877",
"password": "holaa",
"created_at": "2016-07-02 11:36:57",
"updated_at": "2016-07-09 09:56:53"
}]
This is my code so far:
private List<cuentaObtener> mCuenta;
btnLogIn.Click += async(object sender, EventArgs e) =>
{
string url = "http://localhost:8000/api/v1/cuenta_ci/" + ci.Text + "";
JsonValue json = await ObtenerCi(url);
private async Task<JsonValue> ObtenerCi(string url)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
request.ContentType = "application/json";
request.Method = "GET";
// Send the request to the server and wait for the response:
using (WebResponse response = await request.GetResponseAsync())
{
// Get a stream representation of the HTTP web response:
using (Stream stream = response.GetResponseStream())
{
// Use this stream to build a JSON document object:
JsonValue jsonDoc = await Task.Run(() => JsonObject.Load(stream));
//Code to convert JsonObject to List<T>
// Return the JSON document:
return jsonDoc;
}
}
This is my class where I want to store values:
public class cuentaObtener
{
public int id_cuenta { get; set; }
public string nombre { get; set; }
public string apellido { get; set; }
public int ci { get; set; }
public int telefono { get; set; }
public string dispositivo_id { get; set; }
public string password { get; set; }
}
How can I achieve this? Thank you in advance!
You need to download this Nuget Package (Right Click Project > Manager Nuget Packages)
Then you can use :
string json = null;
using (StreamReader stream = new StreamReader(response.GetResponseStream()))
{
json = stream.ReadToEnd();
}
List<cuentaObtener> JsonConvert.DeserializeObject<List<cuentaObtener>>(json);
If you're using HttpClient:
var response = await httpClient.GetAsync(url);
string json = await response.Content.ReadAsStringAsync();
List<cuentaObtener> JsonConvert.DeserializeObject<List<cuentaObtener>>(json);
I got the following problem:
I am trying to implement Instagram into my website. However I am stuck on the step where I need to get the Acces token. The api's documentation says I need to request it like this :
curl \-F 'client_id=CLIENT-ID' \
-F 'client_secret=CLIENT-SECRET' \
-F 'grant_type=authorization_code' \
-F 'redirect_uri=YOUR-REDIRECT-URI' \
-F 'code=CODE' \https://api.instagram.com/oauth/access_token
I use ASP.NET so I found this equivalent OAuth 2.0 In .NET With Instagram API:
NameValueCollection parameters = new NameValueCollection();
parameters.Add("client_id", "ssdfsdfsdfsdfsdf");
parameters.Add("client_secret", "sdsdfdsfsdfsdfsdfsdfsdf");
parameters.Add("grant_type", "authorization_code");
parameters.Add("redirect_uri", "http://localhost:2422/LoginsGuests/GetLoginPage");
parameters.Add("code", code);
WebClient client = new WebClient();
var result = client.UploadValues("https://api.instagram.com/oauth/access_token", parameters);
var response = System.Text.Encoding.Default.GetString(result);
However I keep getting:
System.Net.WebException: The remote server returned an error: (400) Bad Request.
What I am i doing wrong?
Almost there the instagram api expects a POST not a GET.
Add the "POST" parameter.
var result = client.UploadValues("https://api.instagram.com/oauth/access_token", "POST", parameters);
Also check the instagram settings -> redirect url.
Then this may help don't forget to add a reference to Newtonsoft.Json. Is in .Net version 4.5.1:
using System;
using System.Collections.Specialized;
using System.Net;
using System.Text;
namespace Instagram
{
public class InstagramClient
{
public InstagramClient(string code)
{
GetToken(code);
}
private void GetToken(string code)
{
using (var wb = new WebClient())
{
var parameters = new NameValueCollection
{
{"client_id", "ClientId"},
{"client_secret", "ClientSecret"},
{"grant_type", "authorization_code"},
{"redirect_uri", "RedirectUri"},
{"code", code}
};
var response = wb.UploadValues("https://api.instagram.com/oauth/access_token", "POST", parameters);
string json = Encoding.ASCII.GetString(response);
try
{
var OauthResponse = (InstagramOAuthResponse) Newtonsoft.Json.JsonConvert.DeserializeObject(json, typeof(InstagramOAuthResponse));
}
catch (Exception ex)
{
//handle ex if needed.
}
}
}
public class InstagramOAuthResponse
{
public string access_token { get; set; }
public User user { get; set; }
}
public class User : System.Security.Principal.IIdentity
{
public string username { get; set; }
public string website { get; set; }
public string profile_picture { get; set; }
public string full_name { get; set; }
public string bio { get; set; }
public string id { get; set; }
public string OAuthToken { get; set; }
public string AuthenticationType
{
get { return "Instagram"; }
}
public bool IsAuthenticated
{
get { return !string.IsNullOrEmpty(id); }
}
public string Name
{
get
{
return String.IsNullOrEmpty(full_name) ? "unknown" : full_name;
}
}
}
}
}
If you prefer HttpWebRequest class:
var request = (HttpWebRequest)WebRequest.Create("https://api.instagram.com/oauth/access_token/");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
var requestDetails = "client_id=" + AppConfig.InstagramClientId;
requestDetails += "&client_secret=" + AppConfig.InstagramClientSecret;
requestDetails += "&grant_type=authorization_code";
requestDetails += "&redirect_uri=" + redirectUrl;
requestDetails += "&code=" + exchangeCode;
byte[] bytes = Encoding.ASCII.GetBytes(requestDetails);
request.ContentLength = bytes.Length;
using (Stream outputStream = request.GetRequestStream())
{
outputStream.Write(bytes, 0, bytes.Length);
}
var response = request.GetResponse();
var code = ((HttpWebResponse)response).StatusCode;
if (code == HttpStatusCode.OK)
{
using (var streamReader = new StreamReader(response.GetResponseStream()))
{
var jsonString = streamReader.ReadToEnd();
var accessToken = ParseAccessToken(jsonString);
return accessToken;
}
}