json problems while reading a facebook page - c#

i`m trying to read a facebook wall using Json, but I get the error-
Cannot access child value on Newtonsoft.Json.Linq.JProperty. Any ideas?
string pageInfo = client.DownloadString(string.Format("https://graph.facebook.com/Pokerfreerollpass?access_token={0} ", accessToken));
string pagePosts = client.DownloadString(string.Format("https://graph.facebook.com/Pokerfreerollpass/posts?access_token={0} ", accessToken));
//Console.Write(pagePosts);
var result = JsonConvert.DeserializeObject<dynamic>(pagePosts);
foreach (var item in result)
{
Console.WriteLine(item["body"]["message"].ToString());
}
Errors Show on line Console.WriteLine(item["bo"message"].ToString());
Bellow I'm adding the text that shows when I change the last line tody"][
foreach (var item in result.Children())
{
Console.WriteLine(item.ToString());
}
"id": "105458566194298_494770977263053",
"from": {
"id": "105458566194298",
"category": "Community",
"name": "Poker freeroll password"
},
"message": "?100 ,?200 ,?500 Redbet Freeroll on RBP\nMore Info: http://goo.g
l/RMMxY (Boss Media network)\n\nall tourneys under 500 players\n27/05/2013 20:00
CET ?100 Redbet Freeroll\n28/05/2013 20:00 CET ?200 Redbet Freeroll\n29/05/2013
20:00 CET ?100 Redbet Freeroll\n30/05/2013 20:00 CET ?500 Redbet Freeroll",
"privacy": {
"value": ""
},
"type": "status",
"status_type": "mobile_status_update",
"created_time": "2013-05-27T17:04:35+0000",
"updated_time": "2013-05-27T17:04:35+0000",
"likes": {
"data": [
{
"name": "Carlos Alberto Mendoza Alvarez",
"id": "1417267896"
},
{
"name": "????? ??????",
UPDATE:
Pageposts.Tostring
88 on showdown in tournament.. maybe it's is not working in this tournament?
i need to write to support?","can_remove":false,"created_time":"2013-06-01T1
8:50+0000","like_count":0,"user_likes":false},{"id":"497024067037744_77740391
from":{"id":"105458566194298","category":"Community","name":"Poker freeroll p
word"},"message":"\u041f\u0430\u0432\u0435\u043b \u0418\u0432\u0430\u043d\u04
u0432 Anyway please contact customer support","message_tags":[{"id":"1000012
69275","name":"\u041f\u0430\u0432\u0435\u043b \u0418\u0432\u0430\u043d\u043e\
32","type":"user","offset":0,"length":12}],"can_remove":false,"created_time":
13-06-01T19:20:22+0000","like_count":0,"user_likes":false},{"id":"49702406703
4_77744788","from":{"name":"\u041f\u0430\u0432\u0435\u043b \u0418\u0432\u0430
43d\u043e\u0432","id":"100001204869275"},"message":"Answer from support: \"At
is moment we do not offer any promotion with the features at issue.\"\nSo thi
onus doesn't exists in this tournament.","can_remove":false,"created_time":"2
-06-03T09:31:34+0000","like_count":0,"user_likes":false},{"id":"4970240670377
77745216","from":{"id":"105458566194298","category":"Community","name":"Poker
eeroll password"},"message":"\u041f\u0430\u0432\u0435\u043b \u0418\u0432\u043
043d\u043e\u0432 ok","message_tags":[{"id":"100001204869275","name":"\u041f\
30\u0432\u0435\u043b \u0418\u0432\u0430\u043d\u043e\u0432","type":"user","off
":0,"length":12}],"can_remove":false,"created_time":"2013-06-03T13:25:35+0000
like_count":0,"user_likes":false}],"paging":{"cursors":{"after":"Ng==","befor
"Mw=="}}}}],"paging":{"previous":"https:\/\/graph.facebook.com\/1054585661942
/posts?access_token=177257699103893|_qFGs75Mlif-Y2rwvK1RsCs_mMY&limit=25&sinc
370346635&__previous=1","next":"https:\/\/graph.facebook.com\/105458566194298
osts?access_token=177257699103893|_qFGs75Mlif-Y2rwvK1RsCs_mMY&limit=25&until=
0108995"}}
code: is Now
client.DownloadString(string.Format("https://graph.facebook.com/Pokerfreerollpass?access_token={0} ", accessToken));
string pagePosts = client.DownloadString(string.Format("https://graph.facebook.com/Pokerfreerollpass/posts?access_token={0} ", accessToken));
//Console.Write(pagePosts);
var result = JsonConvert.DeserializeObject<dynamic>(pagePosts);
//// dynamic message="";
foreach (var item in result.Children())
{
result = JsonConvert.DeserializeObject<RootObject>(item.ToString());
var message = result.message.ToString();
Console.Write(message);
}
// Console.Write(message.ToString());
Console.Read();
}
public class From
{
public string id { get; set; }
public string category { get; set; }
public string name { get; set; }
}
public class Privacy
{
public string value { get; set; }
}
public class Datum
{
public string name { get; set; }
public string id { get; set; }
}
public class Likes
{
public List<Datum> data { get; set; }
}
public class RootObject
{
public string id { get; set; }
public From from { get; set; }
public string message { get; set; }
public Privacy privacy { get; set; }
public string type { get; set; }
public string status_type { get; set; }
public string created_time { get; set; }
public string updated_time { get; set; }
public Likes likes { get; set; }
}
}
}

I don't see a body property. Try using item["message"].ToString() instead.

if you have the json you can create mapping classes for that. below will give you idea how you can do that.
var result = JsonConvert.DeserializeObject<RootObject>(item.ToString());
var message = result.message;
Generated classes for given json from http://json2csharp.com/
public class From
{
public string id { get; set; }
public string category { get; set; }
public string name { get; set; }
}
public class Privacy
{
public string value { get; set; }
}
public class Datum
{
public string name { get; set; }
public string id { get; set; }
}
public class Likes
{
public List<Datum> data { get; set; }
}
public class RootObject
{
public string id { get; set; }
public From from { get; set; }
public string message { get; set; }
public Privacy privacy { get; set; }
public string type { get; set; }
public string status_type { get; set; }
public string created_time { get; set; }
public string updated_time { get; set; }
public Likes likes { get; set; }
}
Update :
foreach (var item in result.Children())
{
var result = JsonConvert.DeserializeObject<RootObject>(item.ToString());
var message = result.message;
}

Related

Deserialize JSON to List

I have this Json:
{
"trades": [
{
"id": "4004",
"instrument": "EUR_USD",
"price": "1.08938",
"openTime": "2020-02-26T12:15:32.309973340Z",
"initialUnits": "1",
"initialMarginRequired": "0.0363",
"state": "OPEN",
"currentUnits": "1",
"realizedPL": "0.0000",
"financing": "0.0000",
"dividendAdjustment": "0.0000",
"unrealizedPL": "-0.0026",
"marginUsed": "0.0362",
"takeProfitOrder": {
"id": "4005",
"createTime": "2020-02-26T12:15:32.309973340Z",
"type": "TAKE_PROFIT",
"tradeID": "4004",
"price": "1.09099",
"timeInForce": "GTC",
"triggerCondition": "DEFAULT",
"state": "PENDING"
}
}
],
"lastTransactionID": "4010"
}
And Classes:
public class TakeProfitOrder
{
public string id { get; set; }
public string createTime { get; set; }
public string type { get; set; }
public string tradeID { get; set; }
public string price { get; set; }
public string timeInForce { get; set; }
public string triggerCondition { get; set; }
public string state { get; set; }
}
public class Trade
{
public string id { get; set; }
public string instrument { get; set; }
public string price { get; set; }
public string openTime { get; set; }
public string initialUnits { get; set; }
public string initialMarginRequired { get; set; }
public string state { get; set; }
public string currentUnits { get; set; }
public string realizedPL { get; set; }
public string financing { get; set; }
public string dividendAdjustment { get; set; }
public string unrealizedPL { get; set; }
public string marginUsed { get; set; }
public TakeProfitOrder takeProfitOrder { get; set; }
}
public class RootObject
{
public List<Trade> trades { get; set; }
public string lastTransactionID { get; set; }
}
I deserialize with :
var result = JsonConvert.DeserializeObject<RootObject>(Json);
var price = result.trades.Select(p => p.price).ToList();
price.ForEach(Console.WriteLine);
It works. I can access "price" in "trades", but I do not know how to access the "price" in "takeProfitOrder". I need the value of "price" from "takeProfitOrder" in to a list. I am sure it is something very simple but I cannot figure out how to do it, even after looking at some similar examples.
Can somebody please help me?
It's simple
result.trades.Select(p => p.takeProfitOrder.price)
You should understand better from this example
foreach (Trade trade in result.trades)
{
TakeProfitOrder takeProfitOrder = trade.takeProfitOrder;
Console.WriteLine(takeProfitOrder.price);
}

how can to parse in c# JSON with dynamic key using JSON.NET or any other package

Hi guys i am having problem how can i parse JSON with this data because as you can see below the data_0 key is incrementing i am having confusion how can i parse it using my models
{
"status": {
"connection_status": "successful",
"operation_status": "successful",
"Customer": {
"data_0": {
"id": "123321",
"FirstName": "testFirstname",
"LastName": "testlastname"
},
"data_1": {
"id": "321123",
"FirstName": "testFirstname",
"LastName": "testlastname",
}
}
}
}
this is my model
public class GetAccountBalanceResponseModel
{
public Stat status { get; set; }
}
public class Stat
{
public string connection_status { get; set; }
public string operation_status { get; set; }
public Custmer Customer { get; set; }
}
public class Custmer
{
public Datas data { get; set; } -- i am having problem with this one
}
public class Datas
{
public string id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string email { get; set; }
public string accountBalance { get; set; }
}
Use Dictionary<string, Datas> for property Customer in Stat class,
public class Stat
{
public string connection_status { get; set; }
public string operation_status { get; set; }
public Dictionary<string, Datas> Customer { get; set; }
}
Usage:
GetAccountBalanceResponseModel model = JsonConvert.DeserializeObject<GetAccountBalanceResponseModel>(json);
foreach (var item in model.status.Customer)
{
Console.WriteLine("Key: " + item.Key);
Console.WriteLine("Id: " + item.Value.id);
Console.WriteLine("FirstName: " + item.Value.FirstName);
Console.WriteLine("LastName: " + item.Value.LastName);
Console.WriteLine();
}
Output:
Just change your Stat class a little:
public class Stat
{
public string connection_status { get; set; }
public string operation_status { get; set; }
public Dictionary<string, Datas> Customer { get; set; }
}
Then you can use something like stat.Customer["data_0"].email

C# Deserialize Facebook JSON starting with random key

Hello still a newb (student) to C#, I was wondering how to deserialize this kind of JSON data (with JsonConvert and a model class)
JSON example:
{
"435321729828514": {
"id": "435321729828514",
"name": "Kursaal Oostende"
},
"56302776046": {
"id": "56302776046",
"name": "Caf\u00e9 Charlatan"
}
}
Repository class:
public class FB
{
public async static Task<FBModel> Entries(string ids)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(#"https://graph.facebook.com/v2.8/");
HttpResponseMessage response = await client.GetAsync("?ids="+ ids +"&fields=id,name&access_token=secret_token");
if (response.IsSuccessStatusCode)
{
string s = await response.Content.ReadAsStringAsync();
FBModel entries = JsonConvert.DeserializeObject<FBModel>(s);
return entries;
}
else
return null;
}
}
}
Model:
public class FBModel
{
public string ID { get; set; }
public string Name { get; set; }
public override string ToString()
{
return ID + ": " + Name;
}
}
MainPage.xaml (call):
private static FBModel _entries; // global variable
// ...
_entries = await FB.Entries(ids_to_pass);
--------- Solved (model) ----------
public class FBModel
{
#region properties
public string Id { get; set; }
public string Name { get; set; }
public Events Events { get; set; }
#endregion
}
public class Events
{
#region props
public List<Datum> Data { get; set; }
public Paging Paging { get; set; }
#endregion
}
public class Datum
{
#region props
public string Description { get; set; }
public string End_time { get; set; }
public string Name { get; set; }
public Place Place { get; set; }
public string Start_time { get; set; }
public string Id { get; set; }
#endregion
}
public class Place
{
#region props
public string Id { get; set; }
public string Name { get; set; }
public Location Location { get; set; }
#endregion
}
public class Location
{
#region props
public string City { get; set; }
public string Country { get; set; }
public double Latitude { get; set; }
public double Longitude { get; set; }
public string Street { get; set; }
public string Zip { get; set; }
#endregion
}
#region not important
public class Paging
{
#region props
public Cursors Cursors { get; set; }
public string Next { get; set; }
#endregion
}
public class Cursors
{
#region props
public string Before { get; set; }
public string After { get; set; }
#endregion
}
-------- Solved (complete JSON) ----------
{
"435321729828514": {
"id": "435321729828514",
"name": "Kursaal Oostende",
"events": {
"data": [
{
"description": "CHRISTOFF, ...",
"end_time": "2017-11-25T23:00:00+0100",
"name": "Vrienden Voor Het Leven",
"place": {
"name": "Kursaal Oostende",
"location": {
"city": "Oostende",
"country": "Belgium",
"latitude": 51.2312299,
"longitude": 2.9126599,
"street": "Westhelling 12",
"zip": "8400"
},
"id": "435321729828514"
},
"start_time": "2017-11-25T20:00:00+0100",
"id": "161310354323914"
}
],
"paging": {
"cursors": {
"before": "MTYxMzEwMzU0MzIzOTE0",
"after": "MTYxMzEwMzU0MzIzOTE0"
},
"next": "https://graph.facebook.com/v2.8/435321729828514/events?access_token=EAAH2ZAZAq846IBAM9ZAX0LWpDxlzFaPr8jNOxDct2tZBw7YJAtnYxIlVud67hiXI51ybmhLcz4AhMtiVxZBBcPixx9wB9ntF1ZBRhSIuSxeUu83mg6tZBc0BseLpdmkWuu7bohQxXvvLUe67pjETnqDOj8PzFZAXHHAyqEqYrWOXvAZDZD\u002522&pretty=1&limit=1&after=MTYxMzEwMzU0MzIzOTE0"
}
}
}
}
-------- Solved (Repository) ---------
public async static Task<List<FBModel>> Entries(string ids)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(#"https://graph.facebook.com/v2.8/");
HttpResponseMessage response = await client.GetAsync("?ids="+ ids +"&fields=id,name,events.limit(60)&access_token=secret_token");
if (response.IsSuccessStatusCode)
{
string s = await response.Content.ReadAsStringAsync();
var entries = JsonConvert.DeserializeObject<Dictionary<string, FBModel>>(s);
List<FBModel> data = entries.Select(item => item.Value).ToList();
return data;
}
else
return null;
}
}
This is what you have to do.
Step 1: Convert your json to Dictionary.
var dataDictionary = JsonConvert.DeserializeObject<Dictionary<string, FBModel>>(yourJsonstring);
Step 2: Then get list of object
List<FBModel> data=new List<FBModel>();
foreach (var item in dataDictionary)
{
data.Add(item.Value);
}
Step 2 can be done as a linq query
List<FBModel> data= dataDictionary.Select(item => item.Value).ToList();
Update
your class structure should be like below to access the event data.
public class FBModel
{
public string ID { get; set; }
public string Name { get; set; }
public Events Events { get; set; }
public override string ToString()
{
return ID + ": " + Name;
}
}
public class Events
{
public List<Data> Data { get; set; }
}
public class Data
{
public string Description { get; set; }
public string End_Time { get; set; }
public string Name { get; set; }
public Place Place { get; set; }
public string Start_Time { get; set; }
public string Id { get; set; }
}
public class Place
{
public string Name { get; set; }
public Location Location { get; set; }
}
public class Location
{
public string City { get; set; }
public string Country { get; set; }
public string Latitude { get; set; }
public string Longitude { get; set; }
public string Street { get; set; }
public string Zip { get; set; }
}

Json Deserialize Exception

I'm trying to run the following code, but get an exception:
An exception of type 'Newtonsoft.Json.JsonSerializationException'
occurred in Newtonsoft.Json.DLL but was not handled in user code
Additional information: Error converting value "country" to type
'LocalGasPrices.Station'. Path '', line 1, position 9.
var jsonObj = JObject.Parse(URL);
var results = jsonObj["stations"].Children().Values();
var details = new List<Station>();
foreach (JToken result in results)
{
var st = result.ToString();
var searchResult = JsonConvert.DeserializeObject<Station>(st);
details.Add(searchResult);
}
foreach (Station s in details)
{
this.txtDebug.Text += s.address;
}
And here are the classes for the JsonDeserialization:
public class Status
{
public string error { get; set; }
public int code { get; set; }
public string description { get; set; }
public string message { get; set; }
}
public class GeoLocation
{
public string city_id { get; set; }
public string city_long { get; set; }
public string region_short { get; set; }
public string region_long { get; set; }
public string country_long { get; set; }
public string country_id { get; set; }
public string region_id { get; set; }
}
public class Station
{
public string country { get; set; }
public string price { get; set; }
public string address { get; set; }
public string diesel { get; set; }
public string id { get; set; }
public string lat { get; set; }
public string lng { get; set; }
public string station { get; set; }
public string region { get; set; }
public string city { get; set; }
public string date { get; set; }
public string distance { get; set; }
}
public class RootObject
{
public Status status { get; set; }
public GeoLocation geoLocation { get; set; }
public List<Station> stations { get; set; }
}
And here is an example of the JSON response:
{
"status": {
"error": "NO",
"code": 200,
"description": "none",
"message": "Request ok"
},
"geoLocation": {
"city_id": "147",
"city_long": "Saint-Laurent",
"region_short": "QC",
"region_long": "Quebec",
"country_long": "Canada",
"country_id": "43",
"region_id": "35"
},
"stations": [
{
"country": "Canada",
"price": "3.65",
"address": "3885, Boulevard Saint-Rose",
"diesel": "0",
"id": "33862",
"lat": "45.492367",
"lng": "-73.710915",
"station": "Shell",
"region": "Quebec",
"city": "Saint-Laurent",
"date": "3 hours agp",
"distance": "1.9km"
}
]
}
I believe you don't need .Values() in results, .Values() selected the properties of the station.
var results = jsonObj["stations"].Children();
Use the following:
var details = jsonObj["stations"].Select(t => t.ToObject<Station>()).ToList();
change Your class name as "stations" which you get in JSON.
try something like this:
public class JsonData
{
[JsonProperty("status")]
public JObject Status{get;set;}
[JsonProperty("geoLocation")]
public JObject Location{get;set;}
[JsonProperty("stations")]
public List<JObject> Stations{get;set;}
}
public class FinalData
{
public Status StatusField{get;set;}
public GeoLocation LocationField{get;set;}
public List<Station> StationsList{get;set;}
}
}
then
JsonSerializer serializer = new JsonSerializer();
JsonReader reader = new JsonTextReader(new StringReader(your_json));
var jObj = serializer.Deserialize<JsonData>(reader);
var result = new FinalData();
result.StatusField = new Status{ message = jObj.Status["message"].ToString();};
result.LocationField = new GeoLocation{jObj.location["city_id"].ToString();};
result.StationsList = new List<Station>();
foreach(var row = jObj.Stations)
{
result.StationsList.Add(new Station{country = row["country"].ToString(), address = row["address"].ToString()};
}
Try the following.
First create a RootObject
public class RootObject
{
public RootObject(){}
public Status status {get;set;}
public GeoLocation GeoLocation {get;set;}
public List<Stations> Stations {get;set;}
}
public class Status
{
public Status(){}
[JsonProperty("error")]
public string Error {get;set;}
//all properties
}
public class GeoLocation
{
public GeoLocation{get;set;}
[JsonProperty("city_id")]
public int CityId {get;set;}
//all properties
}
public class Station
{
public Station(){}
// all properties just like previous classes
}
Then:
var result = serializer.DeserializeObject<RootObject>(jsonInput);
this should give you the RootObject with a status, GeoLocation and list of stations.

Converting Json code to C# (numbers as keys)

I get some json code from web services in Windows Phone 8. I generate my entities class thanks to the site json2csharp (http://json2csharp.com/). But there is a web service that has strange json code, like this. There is numbering as keys (0,1,2):
{
"service": "MainMapService",
"func": "getPlacesByAxes",
"result": {
"0": {
"id": "13478",
"date": "0",
"id_cat": "1",
"id_cat_sub": "0",
"id_user": "0",
},
"2": {
"id": "23272",
"date": "0",
"id_cat": "1",
"id_cat_sub": "0",
"id_user": "667"
},
"1": {
"id": "21473",
"date": "0",
"id_cat": "1",
"id_cat_sub": "0",
"id_user": "0"
}
},
"args": [
"1",
"50.8",
"4.5",
"1"
]
}
And json2csharp generates classes like this... Each class for a number:
public class __invalid_type__0
{
public string id { get; set; }
public string date { get; set; }
public string id_cat { get; set; }
public string id_cat_sub { get; set; }
public string id_user { get; set; }
}
public class __invalid_type__2
{
public string id { get; set; }
public string date { get; set; }
public string id_cat { get; set; }
public string id_cat_sub { get; set; }
public string id_user { get; set; }
}
public class __invalid_type__1
{
public string id { get; set; }
public string date { get; set; }
public string id_cat { get; set; }
public string id_cat_sub { get; set; }
public string id_user { get; set; }
}
public class Result
{
public __invalid_type__0 __invalid_name__0 { get; set; }
public __invalid_type__2 __invalid_name__2 { get; set; }
public __invalid_type__1 __invalid_name__1 { get; set; }
}
public class RootObject
{
public string service { get; set; }
public string func { get; set; }
public Result result { get; set; }
public List<string> args { get; set; }
}
So, the problem comes from the numbering keys and there may be several numbers. Do you know how can I resolve this? I can't change the Json code...
Thank you in advance
This is far from elegant, but give it a try.
So, what is my idea:
I have created two classes
RootObject helper
public class YourJsonClass
{
public string service { get; set; }
public string func { get; set; }
public dynamic result { get; set; }
public string[] args { get; set; }
}
result helper
public class Item
{
public string id { get; set; }
public string date { get; set; }
public string id_cat { get; set; }
public string id_cat_sub { get; set; }
public string id_user { get; set; }
}
I'm using newtonsoft json
var m_res = JsonConvert.DeserializeObject<YourJsonClass>(YourJsonResponce);
foreach (dynamic numb in m_res.result)
{
string m_name = numb.Name; // it will be "1", "0" or whatever
string h = numb.Value.ToString();
var m_value = JsonConvert.DeserializeObject<Item>(h);
}
... indeed there are better ways, but i hope this will help (:

Categories