facebook graph api deserialization for page search - c#

I'm using Facebook graph API to search pages, https://graph.facebook.com/search?q=platform&type=page
Here is the response in json, i've included only one:
{
"data": [
{
"category": "Media/news/publishing",
"category_list": [
{
"id": "108366235907857",
"name": "Newspaper"
}
],
"name": "Arab News",
"id": "10250877124"
}
],
"paging": {
"next": "https://graph.facebook.com/search?limit=1&offset=1&type=page&q=media&__after_id=10250877124"
}
}
Now, here are my classes in C#:
public class CategoryList
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
}
public class DataRoot
{
[JsonProperty("category")]
public string Category { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("category_list")]
public CategoryList[] CategoryList { get; set; }
}
public class Paging
{
[JsonProperty("next")]
public string Next { get; set; }
}
public class FacebookPageResults
{
[JsonProperty("data")]
public DataRoot[] Data { get; set; }
[JsonProperty("paging")]
public Paging Paging { get; set; }
}
Here is the odd thing, when i try to deserialize it
FacebookPageResults response = new JavaScriptSerializer().Deserialize<FacebookPageResults>(res); , the CategoryList is always null, doesn't even fill up. I have tried with List CategoryList {get; set;} but the result is the same?
Any help or workaround about thi

If anyone is wondering, i found the solution:
FacebookPageResults response = JsonConvert.DeserializeObject(res);
This works

FacebookPageResults response = JsonConvert.DeserializeObject(res.ToString());

Related

Deserialize json to List<object> in C#

I have the following JSON string
{
"data": [
{
"symbol": "1COV.GE",
"exposure": "0",
"makerExposure": "-2028",
"takerExposure": "2028",
"makerPnl": "447.6688",
"takerPnl": "-447.6688",
"makerPositions": [
{
"name": "IB_001",
"position": "-2028",
"vwap": "47.41",
"pnl": "447.6688"
}
],
"takerPositions": [
{
"name": "MT5_1",
"position": "2028",
"vwap": "47.41",
"pnl": "-447.6688"
}
]
},
{
"symbol": "A",
"exposure": "0",
"makerExposure": "-10",
"takerExposure": "10",
"makerPnl": "-4.6",
"takerPnl": "4.6",
"makerPositions": [
{
"name": "IB_002",
"position": "-10",
"vwap": "136.78",
"pnl": "-4.6"
}
],
"takerPositions": [
{
"name": "MT5_1",
"position": "10",
"vwap": "136.78",
"pnl": "4.6"
}
],
"total": 2
}
}
And my goal is to serialize it into a List of object from the NODE "Data":
I have the classes that map the data node fields:
public class Positions
{
public string name { get; set; }
public string position { get; set; }
public string vwap { get; set; }
public string pnl { get; set; }
}
public class ExPositions
{
public string symbol { get; set; }
public string exposure { get; set; }
public string makerExposure { get; set; }
public string takerExposure { get; set; }
public string makerPnl { get; set; }
public string takerPnl { get; set; }
public OZPositions makerPositions { get; set; }
public OZPositions takerPositions { get; set; }
}
Do you have any ideas how I can convert the node "data" to list of "ExPositions" objects, eg. List
I've did this but so far it throws an error
var positions = JsonSerializer.Deserialize<ExPositions>(json_string);
There is an error in your json - it's missing a closing ] for the array (I'll assume it's a typo).
The real problem is that you need a wrapper class to represent the data node of the json which should contain a list (or array) of ExPositions. The makerPositions and takerPositions should also become lists (or arrays) too. Add the following class and update the position properties of ExPositions:
public class Data
{
public List<ExPositions> data { get; set; }
}
// change positions to use a List too
public class ExPositions
{
...
public List<Positions> makerPositions { get; set; }
public List<Positions> takerPositions { get; set; }
}
Then you can deserialize using:
var result = JsonSerializer.Deserialize<Data>(json);
It's not clear where the ""total"": 2 property should be in your models (it's not clear in the json because of the issue I mentioned), you could add it to the Data class above (if it belongs there).
Online demo
Try with:
public class Positions
{
public string name { get; set; }
public string position { get; set; }
public string vwap { get; set; }
public string pnl { get; set; }
}
public class ExPositions
{
public string symbol { get; set; }
public string exposure { get; set; }
public string makerExposure { get; set; }
public string takerExposure { get; set; }
public string makerPnl { get; set; }
public string takerPnl { get; set; }
public Positions makerPositions { get; set; }
public Positions takerPositions { get; set; }
}
public class YourResult{
public ExPositions data { get; set; }
public int total { get; set; }
}
And then call:
var positions = JsonSerializer.Deserialize<YourResult>(json_string);
As haldo mentioned, there is a typo in your JSON. To quickly parse and validate your JSON data, you can use any online JSON parsers to validate your JSON data. I usually use the chrome extension JSON Viewer Pro.
Also, in the link that haldo provided to the .NET Fiddle for the demo, there is a trailing comma in JSON data which JSON deserializers might not ignore.
Here is the link to the edited demo that haldo provided.
Edited Demo

Pass Nested Deserialized JSON from Controller to View

After using HttpClient class to convert my JSON to a string and deserialize it with
var response = Res.Content.ReadAsStringAsync().Result;
data = JsonConvert.DeserializeObject<List<Employee>>(response);
How do I pass the data that I receive in the Controller from the call using the Model below to the View?
public class RuleType
{
public int Id { get; set; }
public string Description { get; set; }
public bool Inactive { get; set; }
}
public class RuleCategory
{
public int Id { get; set; }
public string Description { get; set; }
public bool Inactive { get; set; }
}
public class Employee
{
public string Description { get; set; }
public object EndDateTime { get; set; }
public int Id { get; set; }
public bool Inactive { get; set; }
public int RuleAction { get; set; }
public DateTime StartDateTime { get; set; }
public RuleType RuleType { get; set; }
public RuleCategory RuleCategory { get; set; }
}
Here is one object from the call
[
{
"Description": "Test Description",
"EndDateTime": null,
"Id": 1,
"Inactive": false,
"RuleAction": -2,
"StartDateTime": "2017-01-06T14:58:58Z",
"RuleType": {
"Id": 6,
"Description": "Test Description",
"Inactive": false
},
"RuleCategory": {
"Id": 1,
"Description": "Description",
"Inactive": false
}
}
]
Not sure if I'm missing something, but if you have an object you want to return to the view from the controller, you simply:
return View(viewModel); // in your case viewModel = 'data'
As others have said here already, you should be deserializing the JSON into a RootObject instead of an Employee like so:
var response = Res.Content.ReadAsStringAsync().Result;
var data = JsonConvert.DeserializeObject<List<RootObject>>(response);
You can then pass the model into the view using just:
return View(data)
You should also consider renaming RootObject into something more useful (such as employee?) as RootObject is not a very useful or descriptive name.

Retrieve the information from a nested JSON value

So I'm calling the LinkedIn API to get the profile data and it retrieves a JSON.
{
"firstName": "Cristian Viorel",
"headline": ".NET Developer",
"location": {
"country": {"code": "dk"},
"name": "Northern Region, Denmark"
},
"pictureUrls": {
"_total": 1,
"values": ["https://media.licdn.com/mpr/mprx/0_PXALDpO4eCHpt5z..."]
}
}
I can use student.firstname, student.headline. How can I get the name of the location, or the value of the pictureUrl ?
Something like student.location.name or student.pictureUrls.values ?
Pretty easy with Json.Net. You first define your model:
public class Country
{
public string code { get; set; }
}
public class Location
{
public Country country { get; set; }
public string name { get; set; }
}
public class PictureUrls
{
public int _total { get; set; }
public List<string> values { get; set; }
}
public class JsonResult
{
public string firstName { get; set; }
public string headline { get; set; }
public Location location { get; set; }
public PictureUrls pictureUrls { get; set; }
}
Then you simply parse your Json data:
string json = #"{
'firstName': 'Cristian Viorel',
'headline': '.NET Developer',
'location': {
'country': {'code': 'dk'},
'name': 'Northern Region, Denmark'
},
'pictureUrls': {
'_total': 1,
'values': ['https://media.licdn.com/mpr/mprx/0_PXALDpO4eCHpt5z...']
}
}";
JsonResult result = JsonConvert.DeserializeObject<JsonResult>(json);
Console.WriteLine(result.location.name);
foreach (var pictureUrl in result.pictureUrls.values)
Console.WriteLine(pictureUrl);
For the name yes, but for picture you need a for loop or if you just want the first item student.pictureUrls.values[0] (values seems to be an array).

What is the correct class structure in C# to convert this Json into?

I have the following Json below coming from a Rest service and I am trying to deserialize it into a C# object using this code:
var _deserializer = new JsonDeserializer();
var results = _deserializer.Deserialize<Report>(restResponse);
The deserialize method keeps returning null which tells me that my C# object is not structured correctly.
Below is the Json and my latest attempt at the C# definition.
{
"Report": [
{
"ID": "0000014",
"Age": "45",
"Details": [
{
"Status": "Approved",
"Name": "Joe"
},
{
"Status": "Approved",
"Name": "Bill"
},
{
"Status": "Submitted",
"Name": "Scott"
}
]
},
{
"ID": "10190476",
"Age": "40",
"Details": [
{
"Status": "Approved",
"Name": "Scott"
}
]
},
{
"ID": "10217480",
"Age": "40",
"Details": [
{
"Status": "Approved",
"Name": "Scott"
}
]
}
]
}
Here is my C# object:
public class Report
{
public List<WorkItem> Item= new List<WorkItem>();
}
public class WorkItem
{
public string ID { get; set; }
public int Age { get; set; }
public List<Details> Details { get; set; }
}
public class Details
{
public string Status { get; set; }
public string Name { get; set; }
}
Can someone advise what is wrong with my C# object definition to make this json deserialize correctly?
I would recommend using Json2Csharp.com to generate the classes.
public class Detail
{
public string Status { get; set; }
public string Name { get; set; }
}
public class Report
{
public string ID { get; set; }
public string Age { get; set; }
public List<Detail> Details { get; set; }
}
public class RootObject
{
public List<Report> Report { get; set; }
}
Try changing the Report class like so (The class name can be anything, the property must be Report)
public class WorkReport
{
public List<WorkItem> Report;
}
It should be trying to deserialize at the root into a class with an array/list of of workitem objects called Report.
You can try something like this. I have changed List to Dictionary You don't have a class defined at the root level. The class structure needs to match the entire JSON, you can't just deserialize from the middle. Whenever you have an object whose keys can change, you need to use a Dictionary. A regular class won't work for that; neither will a List.
public class RootObject
{
[JsonProperty("Report")]
public Report Reports { get; set; }
}
public class Report
{
[JsonProperty("Report")]
public Dictionary<WorkItem> Item;
}
public class WorkItem
{
[JsonProperty("ID")]
public string ID { get; set; }
[JsonProperty("Age")]
public int Age { get; set; }
[JsonProperty("Details")]
public Dictionary<Details> Details { get; set; }
}
public class Details
{
[JsonProperty("Status")]
public string Status { get; set; }
[JsonProperty("Name")]
public string Name { get; set; }
}
Then, deserialize like this:
Report results = _deserializer.Deserialize<Report>(restResponse);

Converting Facebook feed from JSON to typed objects with JSON.NET

The problem is, I receive a list of posts from facebook (page feed) which occasionally holds multiple comments in an array inside the post object. Only the first comment of the post gets parsed correctly. Somehow the second and later comments don't get parsed.
This is the JSON I'm going on about:
{
"data": [ //Root object
{ //Post object
"id": "153411918116843_304953306296036",
"from": {
"category": "Sports/recreation/activities",
"category_list": [
{
"id": "124887510918208",
"name": "Swimming Pool"
}
],
"name": "Twentebad",
"id": "153411918116843"
},
"link": "http://dlvr.it/5bBKPx",
"picture": "irrelevant",
"message": "Onderzoek renovatie Twentebad! http://dlvr.it/5bBKPx",
"created_time": "2014-05-07T09:44:18+0000",
"comments": { // Collective comments object
// Actual comments objects in array !!!!! ONLY FIRST GETS PARSED !!!!
"data": [
{ //Comment object
"id": "304953306296036_304959069628793",
"from": {
"id": "884483928243965",
"name": "Selena Suzan Valentino"
},
"message": "Twentepalace",
"can_remove": false,
"created_time": "2014-05-07T10:32:26+0000",
"like_count": 0,
"user_likes": false
},
{ Unparsed comment object
"id": "304953306296036_305126702945363",
"from": {
"id": "884483928243965",
"name": "Selena Suzan Valentino"
},
"message": "Na baantjes trekken vooral heerlijk...",
"can_remove": false,
"created_time": "2014-05-08T09:12:43+0000",
"like_count": 0,
"user_likes": false
},
{ //Unparsed comment object
"id": "304953306296036_305126622945371",
"from": {
"id": "884483928243965",
"name": "Selena Suzan Valentino"
},
"message": "Wil infrarood sauna weer terug komt...",
"can_remove": false,
"created_time": "2014-05-08T09:11:20+0000",
"like_count": 0,
"user_likes": false
}
],
"paging": {
"cursors": {
"after": "MQ==",
"before": "Mw=="
}
},
"summary": {
"order": "ranked",
"total_count": 3
}
}
}
]
}
I'm using JSON.NET to parse this json to a typed object list like this:
foreach (JToken facebookItem in data["data"])
{
JToken messageCheck = facebookItem.SelectToken("message", false); //Irrelevante post als er geen inhoud in zit (false = geen error melding indien null)
if (messageCheck != null)
{
itemsToAdd.Add(facebookItem.ToObject<FacebookItem>());
}
}
The FacebookItem class looks like this:
public class FacebookItem
{
public string id { get; set; }
public From from { get; set; }
public string link { get; set; }
public string picture { get; set; }
public string message { get; set; }
public string created_time { get; set; }
public Comments comments { get; set; }
public PostPaging paging { get; set; }
public class PostCategories
{
public string id { get; set; }
public string name { get; set; }
}
public class From
{
public string category { get; set; }
public List<PostCategories> category_list { get; set; }
public string name { get; set; }
public string id { get; set; }
}
public class CommentCategories
{
public string id { get; set; }
public string name { get; set; }
}
//Root of Comments ("data":[ "comments":{ [],{},{} } ])
public class Comments
{
public List<CommentData> data { get; set; } //SHOULD HOLD MORE THAN 1
public CommentPaging paging { get; set; }
public Summary summary { get; set; }
}
//Data gegevens van comments ("data":[ "comments":{ "data":[],{},{} } ])
public class CommentData
{
public string id { get; set; }
public CommentFrom from { get; set; }
public string message { get; set; }
public bool can_remove { get; set; }
public string created_time { get; set; }
public int like_count { get; set; }
public bool user_likes { get; set; }
}
//Data gegevens van ccommenter ("data":[ "comments":{ "data":[ "from":{} ],{},{} } ])
public class CommentFrom
{
public string id { get; set; }
public string name { get; set; }
public string category { get; set; }
public List<CommentCategories> category_list { get; set; }
}
//Paging gegevens van comments ("data":[ "comments":{ [],"paging":{},{} } ])
public class CommentPaging
{
public Cursors cursors { get; set; }
}
//Summary gegevens van comments ("data":[ "comments":{ [],{},"summary":{} } ])
public class Summary
{
public string order { get; set; }
public int total_count { get; set; }
}
public class Cursors
{
public string after { get; set; }
public string before { get; set; }
}
public class PostPaging
{
public string previous { get; set; }
public string next { get; set; }
}
}
Is there a Json.net expert out there that undertands why only the first comment gets parsed?
This is what the debugger show me:
I'll tell you where I live, please come and kill me...
I called the url from localstorage. I changed the url but changes aren't detected so it doesn't get overwritten.
So, why only one comment? I had the comments' limit set to 1 :(
Not as exiting as I hoped this would be.
Hopefully the info provided can help someone in the future.

Categories

Resources