Using JSON.Net (http://www.newtonsoft.com/json/help/html/LINQtoJSON.htm) and the following C# code:
#using Newtonsoft.Json;
#using Newtonsoft.Json.Linq;
#{
var url = "https://graph.facebook.com/v2.2/me&fields=id%2Cname%2Cposts.limit(3)&format=json&method=get&pretty=0&suppress_http_code=1";
var syncClient = new WebClient();
var content = syncClient.DownloadString(url);
JObject facebook = JObject.Parse(content);
//To-Do: Loop each JSON object to get message, image, & link values.
}
How would I loop each JSON object to get message, image, & link values given the following JSON format (http://www.codeshare.io/EvIdN).
You can just use indexer:
foreach (var element in facebook["posts"]["data"])
{
message = element["message"];
image = element["image"];
//etc
}
Here is an example, and by the way your JSON is invalid...
Related
i hope someone can help me. i'm a very beginner to json but i try to build a programm that loads all the posts from a subreddit trough the json file. I dont want to save it in a class so creating the classes from json is not an option as i found that not every subreddit has the same structure obviously.
as my example i use the /r/wallpaper https://www.reddit.com/r/wallpaper/hot.json?count=25
That is my current code but i always get a null result to dat2 when searchin in the JObject
var json = "";
using (WebClient client = new WebClient())
{
json = client.DownloadString("https://www.reddit.com/r/wallpaper/hot.json?count=25");
JObject data = JObject.Parse(json);
string dat2 = data["url"].Value<string>();
}
How can i easily search for all value trough a key ? So for example i can get all the thumbnail from each post.
I'm using Json.NET.
You need to find the children and loop through them. Each child has its own url.
Sample code:
var json = "";
using (WebClient client = new WebClient())
{
json = client.DownloadString("https://www.reddit.com/r/wallpaper/hot.json?count=25");
JObject data = JObject.Parse(json);
var children = data["data"]["children"];
for (var i = 0; i < children.Count(); i++)
{
Console.WriteLine(children[i]["data"]["url"]);
}
}
I'm trying to send List to wcf.
i want to send it as json, is there a way ?
when I'm trying to serialize, i get empty string, why ?
public string ImportXml(List<XmlDocument> docs,string token)
{
Account user = GetCurrentUser(token);
string url = string.Format("{0}ImportXml/{1}", ServiceUrl, user.Unumber);
string contentType = "text/json";
x.Serialize(Console.Out, docs);
string jsonReq = _serializer.Serialize(docs);
bool response = false;
HttpRequestHandler handler = new HttpRequestHandler();
string result = handler.HttpPostWithToken(url, jsonReq, contentType, token);
return result ;
}
Each element of the collection docs before sending into WCF is must be serialized into the JSON for example in this way:
string jsonText = JsonConvert.SerializeXmlNode(doc);
where doc is XmlDocument.
Or for Javascript in this way: Converting between XML and JSON
After you get collection of XmlDocument into WCF method try convert each element of entrance collection:
var documents = new List<XmlDocument>();
foreach (var doc in docs)
{
XmlDocument xmlDoc = JsonConvert.DeserializeXmlNode(doc);
documents.Add(xmlDoc);
}
finnally i got list of strings with xml in it.
it is much better, because that way we can work with anyone, and not only C#.
and i moved to newtonsoft instead JSS.
List<string>
I want to create an app that shows current information, i can get the information using a simple (at least, it looks pretty simple) API.
Now, you can use the API by going to the website, and enter the username. The URL will result in something like this site.web/api/public/user?name=Usename.
on that page is all the information I need, in form of one line of 'code'.
{"uniqueId":"hhus-7723dec98ecb9bc6643f10588e0bb3f4","name":"Username","figureString":"hr-125-40.hd-209-1369.ch-210-64.lg-270-1408.he-3329-1408-1408","selectedBadges":[],"motto":"sample txt","memberSince":"2012-08-25T14:01:04.000+0000","profileVisible":true,"lastWebAccess":null}
I want to extract this information and display it in my program, example:
{"uniqueId":"this is an ID"}
I only want the actual ID to be shown: this is an ID.
Thanks for helping!
The format you're receiving is called JSON. There are lots of libraries to read it easily, the most widely used in C# is JSON.NET.
If you only need to extract one property, you can do something like this:
string json = ...
var obj = JObject.Parse(json);
string uniqueId = obj["uniqueId"].Value<string>();
If you also need the other properties, it's probably easier to use deserialization: create a class with the same properties as the JSON object, and use JsonConvert.DeserializeObject to read the JSON into an instance of the class.
The one line of code you're referring to is JSON data. It's stored in the format "key":"value","key:value","key:value" and so on.
You should take a look at Newtonsoft.Json which helps you do exactly this: parse JSON data :)
https://www.nuget.org/packages/Newtonsoft.Json/
Tying it all together for you...
using System.IO;
using System.Net;
using Newtonsoft.Json.Linq;
...
WebClient client = new WebClient();
Stream stream = client.OpenRead("http://site.web/api/public/user?name=Usename");
StreamReader reader = new StreamReader(stream);
string userJson = reader.ReadLine();
reader.Close();
JObject jObject = JObject.Parse(userJson);
string uniqueId = (string)jObject["uniqueId"];
This is an example of Json. The most type safe way if to deserialize the data to a class you define.
Such a class could look like this:
public class MyClass
{
public string uniqueId { get; set; }
}
If you have the data in a string you can just deserialize it with the Newtonsoft.Json nuget package.
MyClass obj = JsonConvert.Deserialize<MyClass>(myJsonString);
If you get the data from http it is easier to use an client which can do the deserialization for you. Such a client is found in the nuget package Microsoft.AspNet.WebApi.Client
using(var client = new HttpClient())
{
var response = await client.GetAsync(myUrl);
response.EnsureSuccessStatusCode();
MyClass obj = await response.Content.ReadAsAsync<MyClass>();
}
Of course this assumes the server is standards compliant and specifies it's content-type as application/json
Bonus: The classes you deserialize to can be auto generated from example at the site: http://json2csharp.com/ .
Hi I am trying to deserialize an Object from a HttpPost method call inside an authorize attribute.I am using ASP.NET Web Api Framework.
Here is my code:
public override void OnAuthorization(HttpActionContext actionContext)
{
var rezult = DeserializeStream<EvaluationFormDataContract>(actionContext.Request.Content.ReadAsStreamAsync().Result);
}
private T DeserializeStream<T>(Stream stream)
{
var binaryFormatter = new BinaryFormatter();
var rez = binaryFormatter.Deserialize(stream);
var t = (T)binaryFormatter.Deserialize(stream);
return t;
}
When this code gets executed I get this exception when the binaryFormatter tryes to deserialize it:
The input stream is not a valid binary format. The starting contents (in bytes) are: 73-74-75-64-65-6E-74-41-73-73-69-67-6E-6D-65-6E-74 ...
What am I doing wrong?
You are trying to use BinaryFormatter to binary deserialize data which was not binary serialized. From data you sent I see that hex code represents a string.
73-74-75-64-65-6E-74-41-73-73-69-67-6E-6D-65-6E-74 decoded is studentAssignment
This leads me to believe you are doing a simple AJAX call and sending JSON data to WebAPI service.
You need to deserialize the stream using JSON.
Read request content as string
If content is JSON, deserialize it using JSON.NET
var json = actionContext.Request.Content.ReadAsStringAsync().Result;
var m = JsonConvert.DeserializeObject<EvaluationFormDataContract>(json);
If response is not JSON, but form data you can parse it like a query string.
var stringData = actionContext.Request.Content.ReadAsStringAsync().Result;
NameValueCollection data = HttpUtility.ParseQueryString(stringData);
string personId = data["personId"];
I need to have access at the HTML of a Facebook page, to extract from it some data. So, I need to create a WebRequest.
Example:
My code worked well for other sites, but for Facebook, I must be logged in to can access the HTML.
How can I use Firefox data for creating a WebRequest for Facebook page?
I tried this:
List<string> HTML_code = new List<string>();
WebRequest request = WebRequest.Create(URL);
using (WebResponse response = request.GetResponse())
using (StreamReader stream = new StreamReader(response.GetResponseStream()))
{
string line;
while ((line = stream.ReadLine()) != null)
{
HTML_code.Add(line);
}
}
...but the HTML resulted is the HTML of Facebook Home Page when I am not logged in.
If what you are trying to is retrieve the number of likes from a Facebook page, you can use Facebook's Graph API service. Just too keep it simple, this is what I basically did in the code:
Retrieve the Facebook page's data. In this case I used the Coke page's data since it was an example FB had listed.
Parse the returned Json using Json.Net. There are other ways to do this, but this just keeps it simple, and you can get Json.Net over at Codeplex. The documentation that I looked for my code was from this page in the docs. Their documentation will also help you with parsing and serializing even more Json if you need to.
Then that basically translates in to this code. Just note that I left out all the fancy exception handling to keep it simple as using networking is not always reliable! Also don't forget to include the Json.Net library in your project!
Usings:
using System.IO;
using System.Net;
using Newtonsoft.Json.Linq;
Code:
string url = "https://graph.facebook.com/cocacola";
WebClient client = new WebClient();
string jsonData = string.Empty;
// Load the Facebook page info
Console.WriteLine("Connecting to Facebook...");
using (Stream data = client.OpenRead(url))
{
using (StreamReader reader = new StreamReader(data))
{
jsonData = reader.ReadToEnd();
}
}
// Get number of likes from Json data
JObject jsonParsed = JObject.Parse(jsonData);
int likes = (int)jsonParsed.SelectToken("likes");
// Write out the result
Console.WriteLine("Number of Likes: " + likes);