C# Deserialize Facebook JSON starting with random key - c#

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; }
}

Related

How do I compare two JSON Objects to get new JSON for changes like add,delete,change using c#

Can anyone help in getting the output Json by comparing two JSON which has same hierarchy, by showing JStatus as Change, Added, Delete. we have JStatus present in each Json, after comparison it will fill with status "change"/"add"/"delete", the values should be from new (2nd json) for changed objects, and value of old (in case of delete) json1.
please help
1st Base JSON (output should treat this as base JSON)
[{"Decision":{"id":"1","identifier":"Base1","dec_id":10,"JStatus":"","objects":[{"id":"1","identifier":"Base2","JStatus":""},{"id":"2","identifier":"Base3","JStatus":""}]}}]
2nd JSON
[{"Decision":{"id":"2","identifier":"Base1","dec_id":12,"JStatus":"","objects":[{"id":"1","identifier":"Base2","JStatus":"","textitem":[{"id":"1","identifier":"Base3","JStatus":"","objNewActivity":[{"id":"1","identifier":"Base4","JStatus":""}],"objNewGebiedsaanwijzingen":[{"id":"1","identifier":"Base5","JStatus":""}],"objNewBegrippen":[{"id":"1","identifier":"Base6","JStatus":""}],"objNewLocation":null}]}]}}]
OutPut required JSON
[{"Decision":{"id":"2","identifier":"Base1","dec_id":12,"JStatus":"Change","objects":[{"id":"1","identifier":"Base2","JStatus":"","textitem":[{"id":"1","identifier":"Base3","JStatus":"Add","objNewActivity":[{"id":"1","identifier":"Base4","JStatus":"Add"}],"objNewGebiedsaanwijzingen":[{"id":"1","identifier":"Base5","JStatus":"Add"}],"objNewBegrippen":[{"id":"1","identifier":"Base6","JStatus":"Add"}],"objNewLocation":null}]},{"id":"2","identifier":"Base3","JStatus":"Delete"}]}}]
I tried https://www.nuget.org/packages/JsonDiffer following but that only show me changes,
var j1 = JToken.Parse(readJson("Json1.txt"));
var j2 = JToken.Parse(readJson("Json2.txt"));
var diff = JsonDifferentiator.Differentiate(j1, j2, OutputMode.Detailed, showOriginalValues: true);
This is PSEUDO CODE
Because I do not know the specific logic you wish to employ to make your comparisons and/or overwrites.
using Newtonsoft.Json;
using System.Collections.Generic;
namespace StackDemo5
{
public class StackDemo5Main
{
string json1 = "{ \"LoginSettings\": { \"Type\": \"Test\", \"Login\": \"Bitcoin\", \"Password\": \"123456\", \"SHA1Login\": \"Some hash\", \"SHA1Password\": \"Some hash\" }, \"Info1\": {\"Is_Active\": false, \"Amount\": 12 }, \"Info2\": { \"Is_Active\": true, \"Amount\": 41 }}";
string json2 = "{ \"LoginSettings\": { \"Type\": \"\", \"Login\": \"\", \"Password\": \"\", \"SHA1Login\": \"\", \"SHA1Password\": \"\" }, \"Info1\": { \"Is_Active\": false, \"Amount\": 0 }, \"Info2\": { \"Is_Active\": false, \"Amount\": 0 }, \"Info3\": { \"Is_Active\": false, \"Amount\": 0 }, \"Info4\": { \"Is_Active\": false, \"Amount\": 0 }}";
public string CreateJsonAggregate() {
Root first = JsonConvert.DeserializeObject<Root>(json1);
Root second = JsonConvert.DeserializeObject<Root>(json2);
Root third = new Root();
third.LoginSettings = first.LoginSettings;
third.Info1 = first.Info1;
third.Info2 = first.Info2;
third.Info3 = second.Info3;
third.Info4 = second.Info4;
return JsonConvert.SerializeObject(third);
}
public class LoginSettings
{
public string Type { get; set; }
public string Login { get; set; }
public string Password { get; set; }
public string SHA1Login { get; set; }
public string SHA1Password { get; set; }
}
public class Info1
{
public bool Is_Active { get; set; }
public int Amount { get; set; }
}
public class Info2
{
public bool Is_Active { get; set; }
public int Amount { get; set; }
}
public class Info3
{
public bool Is_Active { get; set; }
public int Amount { get; set; }
}
public class Info4
{
public bool Is_Active { get; set; }
public int Amount { get; set; }
}
public class Root
{
public LoginSettings LoginSettings { get; set; }
public Info1 Info1 { get; set; }
public Info2 Info2 { get; set; }
public Info3 Info3 { get; set; }
public Info4 Info4 { get; set; }
}
}
public class StackDemo6 {
public string CreateJsonAggregate()
{
string input1 = "[{\"Decision\":{\"id\":\"1\",\"identifier\":\"Base1\",\"dec_id\":10,\"JStatus\":\"\",\"objects\":[{\"id\":\"1\",\"identifier\":\"Base2\",\"JStatus\":\"\"},{\"id\":\"2\",\"identifier\":\"Base3\",\"JStatus\":\"\"}]}}]";
string input2 = "[{\"Decision\":{\"id\":\"2\",\"identifier\":\"Base1\",\"dec_id\":12,\"JStatus\":\"\",\"objects\":[{\"id\":\"1\",\"identifier\":\"Base2\",\"JStatus\":\"\",\"textitem\":[{\"id\":\"1\",\"identifier\":\"Base3\",\"JStatus\":\"\",\"objNewActivity\":[{\"id\":\"1\",\"identifier\":\"Base4\",\"JStatus\":\"\"}],\"objNewGebiedsaanwijzingen\":[{\"id\":\"1\",\"identifier\":\"Base5\",\"JStatus\":\"\"}],\"objNewBegrippen\":[{\"id\":\"1\",\"identifier\":\"Base6\",\"JStatus\":\"\"}],\"objNewLocation\":null}]}]}}]";
Root input1Deserialized = JsonConvert.DeserializeObject<Root>(input1);
Root input2Deserialized = JsonConvert.DeserializeObject<Root>(input2);
Root resultObject = new Root();
// Build you comparison logic:
int dec_id;
if (input1Deserialized.Decision.dec_id > input2Deserialized.Decision.dec_id)
{
dec_id = input1Deserialized.Decision.dec_id;
}
else
{
dec_id = input2Deserialized.Decision.dec_id;
}
resultObject.Decision.dec_id = dec_id;
//etc.
return JsonConvert.SerializeObject(result);
}
}
// Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
public class ObjNewActivity
{
public string id { get; set; }
public string identifier { get; set; }
public string JStatus { get; set; }
}
public class ObjNewGebiedsaanwijzingen
{
public string id { get; set; }
public string identifier { get; set; }
public string JStatus { get; set; }
}
public class ObjNewBegrippen
{
public string id { get; set; }
public string identifier { get; set; }
public string JStatus { get; set; }
}
public class Textitem
{
public string id { get; set; }
public string identifier { get; set; }
public string JStatus { get; set; }
public List<ObjNewActivity> objNewActivity { get; set; }
public List<ObjNewGebiedsaanwijzingen> objNewGebiedsaanwijzingen { get; set; }
public List<ObjNewBegrippen> objNewBegrippen { get; set; }
public object objNewLocation { get; set; }
}
public class Object
{
public string id { get; set; }
public string identifier { get; set; }
public string JStatus { get; set; }
public List<Textitem> textitem { get; set; }
}
public class Decision
{
public string id { get; set; }
public string identifier { get; set; }
public int dec_id { get; set; }
public string JStatus { get; set; }
public List<Object> objects { get; set; }
}
public class Root
{
public Decision Decision { get; set; }
}
}
The trick is to create a generic model that can hold the most possible data, then serialize an object set from all your input strings, then do some sort of logic comparison, here I just did a comparison on dec_id, because I have no idea what your model does, and I don't speak dutch.
Also do write unit tests to validate your logic, it helps.
If you need to generate a new model object in C#, simply use this website from your template, to get a new class structure:
https://json2csharp.com/

How do I create multi level json and pass it as a web request?

I am attempting to connect to an api and pass it a json request. I wasn't sure how to format the json data so I found a post suggesting json2csharp.com.
So, I used http://json2csharp.com/ to create the classes I needed for the json request data:
curl -v -X POST \
-H "Authorization: APIKEY" \
-H "Content-Type: application/json" \
-d '{
"type": "sale",
"amount": 1112,
"tax_amount": 100,
"shipping_amount": 100,
"currency": "USD",
"description": "test transaction",
"order_id": "someOrderID",
"po_number": "somePONumber",
"ip_address": "4.2.2.2",
"email_receipt": false,
"email_address": "user#home.com",
"create_vault_record": true,
"payment_method": {
"card": {
"entry_type": "keyed",
"number": "4012000098765439",
"expiration_date": "12/20",
"cvc": "999",
"cardholder_authentication": {
"condition": "...",
"eci": "...",
"cavv": "...",
"xid": "...",
}
}
... or ...
"customer": {
"id": "b798ls2q9qq646ksu070",
"payment_method_type": "card",
"payment_method_id": "b798ls2q9qq646ksu080",
"billing_address_id": "b798ls2q9qq646ksu07g",
"shipping_address_id": "b798ls2q9qq646ksu07g"
}
... or ...
"terminal": {
"id": "<terminal id>"
"expiration_date": "12/20",
"cvc": "999",
"print_receipt": "both"
"signature_required": true
}
... or ...
"token": "<tokenizer token goes here>",
... or ...
"ach": {
"routing_number": "490000018",
"account_number": "999999",
"sec_code": "ccd",
"account_type": "checking",
"check_number":"1223",
"accountholder_authentication": {
"dl_state": "IL",
"dl_number": "r500123123"
}
... or ...
"apm": {
"type": "alipay",
"merchant_redirect_url": "http://merchantwebsite.com/",
"locale": "en-US",
"mobile_view": false
}
}
},
"billing_address" : {
"first_name": "John",
"last_name": "Smith",
"company": "Test Company",
"address_line_1": "123 Some St",
"city": "Wheaton",
"state": "IL",
"postal_code": "60187",
"country": "US",
"phone": "5555555555",
"fax": "5555555555",
"email": "help#website.com"
},
"shipping_address" : {
"first_name": "John",
"last_name": "Smith",
"company": "Test Company",
"address_line_1": "123 Some St",
"city": "Wheaton",
"state": "IL",
"postal_code": "60187",
"country": "US",
"phone": "5555555555",
"fax": "5555555555",
"email": "help#website.com"
}
}' \
"URL_GOES_HERE/transaction"
Here are the results from the website:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test
{
public class ApiRequest
{
public class ProcessorSpecific
{
}
public class Card
{
public string id { get; set; }
public string card_type { get; set; }
public string first_six { get; set; }
public string last_four { get; set; }
public string masked_card { get; set; }
public string expiration_date { get; set; }
public string status { get; set; }
public string auth_code { get; set; }
public string processor_response_code { get; set; }
public string processor_response_text { get; set; }
public string processor_type { get; set; }
public string processor_id { get; set; }
public string avs_response_code { get; set; }
public string cvv_response_code { get; set; }
public ProcessorSpecific processor_specific { get; set; }
public DateTime created_at { get; set; }
public DateTime updated_at { get; set; }
}
public class Response
{
public Card card { get; set; }
}
public class BillingAddress
{
public string first_name { get; set; }
public string last_name { get; set; }
public string company { get; set; }
public string address_line_1 { get; set; }
public string address_line_2 { get; set; }
public string city { get; set; }
public string state { get; set; }
public string postal_code { get; set; }
public string country { get; set; }
public string phone { get; set; }
public string fax { get; set; }
public string email { get; set; }
}
public class ShippingAddress
{
public string first_name { get; set; }
public string last_name { get; set; }
public string company { get; set; }
public string address_line_1 { get; set; }
public string address_line_2 { get; set; }
public string city { get; set; }
public string state { get; set; }
public string postal_code { get; set; }
public string country { get; set; }
public string phone { get; set; }
public string fax { get; set; }
public string email { get; set; }
}
public class Data
{
public string id { get; set; }
public string type { get; set; }
public int amount { get; set; }
public int tax_amount { get; set; }
public bool tax_exempt { get; set; }
public int shipping_amount { get; set; }
public int discount_amount { get; set; }
public string payment_adjustment_type { get; set; }
public int payment_adjustment_value { get; set; }
public string currency { get; set; }
public string description { get; set; }
public string order_id { get; set; }
public string po_number { get; set; }
public string ip_address { get; set; }
public bool email_receipt { get; set; }
public string email_address { get; set; }
public string payment_method { get; set; }
public Response response { get; set; }
public string status { get; set; }
public int response_code { get; set; }
public string customer_id { get; set; }
public BillingAddress billing_address { get; set; }
public ShippingAddress shipping_address { get; set; }
public DateTime created_at { get; set; }
public DateTime updated_at { get; set; }
}
public class RootObject
{
public string status { get; set; }
public string msg { get; set; }
public Data data { get; set; }
}
}
}
Here is my code so far:
private void button1_Click(object sender, EventArgs e)
{
var urlx = "https://xxxxx.xxxxxxx.com/api/";
var usr = "xxxxxxxxxxx";
var pwd = "xxxx";
// replace with the TEST class to pass in the required JSON request
// BaSysRequest item = new BaSysRequest();
// item.username = usr;
// item.password = pwd;
string request = JsonConvert.SerializeObject(item);
Uri url = new Uri(string.Format(urlx));
string response = Post(url, request);
if (response != null)
{
Console.WriteLine(response);
}
else
{
Console.WriteLine("nothing");
}
}
public string Post(Uri url, string value)
{
var request = HttpWebRequest.Create(url);
var byteData = Encoding.ASCII.GetBytes(value);
request.ContentType = "application/json";
request.Method = "POST";
try
{
using (var stream = request.GetRequestStream())
{
stream.Write(byteData, 0, byteData.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
return responseString;
}
catch (WebException e)
{
return null;
}
}
public string Get(Uri url)
{
var request = HttpWebRequest.Create(url);
request.ContentType = "application/json";
request.Method = "GET";
try
{
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
return responseString;
}
catch (WebException e)
{
return null;
}
}
How do I populate the ApiRequest and pass in the class? Did I create the class correctly for the json data?
Any suggestion?
Since the payment method can be different types then take advantage of using generics
public class TransactionRequest<T> {
public string type { get; set; }
public long amount { get; set; }
public long tax_amount { get; set; }
public long shipping_amount { get; set; }
public string currency { get; set; }
public string description { get; set; }
public string order_id { get; set; }
public string po_number { get; set; }
public string ip_address { get; set; }
public bool email_receipt { get; set; }
public string email_address { get; set; }
public bool create_vault_record { get; set; }
public Dictionary<string, T> payment_method { get; set; }
public Address billing_address { get; set; }
public Address shipping_address { get; set; }
}
public class Address {
public string first_name { get; set; }
public string last_name { get; set; }
public string company { get; set; }
public string address_line_1 { get; set; }
public string address_line_2 { get; set; }
public string city { get; set; }
public string state { get; set; }
public string postal_code { get; set; }
public string country { get; set; }
public string phone { get; set; }
public string fax { get; set; }
public string email { get; set; }
}
The above class is based on the example request made in the original question.
For each one of the possible payment types create a matching model definition that can be used with the generic type
Like Card for example
public partial class Card {
public string entry_type { get; set; }
public string number { get; set; }
public string expiration_date { get; set; }
public long cvc { get; set; }
public CardholderAuthentication cardholder_authentication { get; set; }
}
public partial class CardholderAuthentication {
public string condition { get; set; }
public string eci { get; set; }
public string cavv { get; set; }
public string xid { get; set; }
}
From there it is just a matter of constructing the request and posting to the desired URL
For example
static Lazy<HttpClient> client = new Lazy<HttpClient>();
private async void button1_Click(object sender, EventArgs e) {
var urlx = "https://xxxxx.xxxxxxx.com/api/";
var usr = "xxxxxxxxxxx";
var pwd = "xxxx";
Card card = new Card();
//populate as needed
TransactionRequest<Card> item = new TransactionRequest<Card>();
//populate as needed
//set payment method accordingly
item.payment_method["card"] = card;
Uri url = new Uri(string.Format(urlx));
string response = await PostAsync(url, item);
if (response != null) {
Console.WriteLine(response);
} else {
Console.WriteLine("nothing");
}
}
public async Task<string> PostAsync<T>(Uri url, T value) {
try {
string json = JsonConvert.SerializeObject(value);
var content = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
var response = await client.Value.PostAsync(url, content);
var responseString = await response.Content.ReadAsStringAsync();
return responseString;
} catch (Exception e) {
//TODO: log error
return null;
}
}
Here's a quick and dirty way of doing a post using HttpClient:
private HttpResponseMessage Post(string url, string path, object content)
{
string serialized = JsonConvert.SerializeObject(content);
StringContent stringContent = new StringContent(serialized, Encoding.UTF8, "application/json");
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(url);
HttpResponseMessage response = Task.Run(() => client.PostAsync(path, stringContent)).Result;
client.Dispose();
return response;
}

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

How to read the json string through C# code in runtime?

{
"StudentInformation": {
"rollNumber": null,
"isClassLeader": false,
"result": "Pass"
},
"CollegeInformation": {
"allClass": ["A", "B"],
"currencyAccepted": "INR",
"calendarDates": [],
"currencyCode": "INR",
"collegeCode": null,
"hasBulidingFundPrices": false,
"hasHostel": false,
"hasSecurityFares": false
},
"Collegetrips": [{
"tripsdate": [{
"departureTripDate": "2017-08-15 00:00:00",
"Places": [{
"destination": "Bombay",
"price": [{
"priceAmount": 1726
}]
}]
}]
}]
}
In the above json file i need to retrieve only "priceAmount": 1726. Please anyone suggest how can able to achieve?
You can use System.Web.Script.Serialization (you need to add a reference to System.Web.Extensions):
dynamic json = new JavaScriptSerializer()
.DeserializeObject(jsonString);
decimal price = json["Collegetrips"][0]
["tripsdate"][0]
["Places"][0]
["price"][0]
["priceAmount"]; // 1726
Note that you can pretty much traverse the json in this manner using indexes and key names.
Hi try this,
public void Main()
{
string sJSON = "{\"StudentInformation\": {\"rollNumber\": null,\"isClassLeader\": false,\"result\": \"Pass\"},\"CollegeInformation\": {\"allClass\": [\"A\", \"B\"],\"currencyAccepted\": \"INR\",\"calendarDates\": [],\"currencyCode\": \"INR\",\"collegeCode\": null,\"hasBulidingFundPrices\": false,\"hasHostel\": false,\"hasSecurityFares\": false},\"Collegetrips\": [{\"tripsdate\": [{\"departureTripDate\": \"2017-08-15 00:00:00\",\"Places\": [{\"destination\": \"Bombay\",\"price\": [{\"priceAmount\": 1726}]}]}]}]}";
Rootobject obj = Newtonsoft.Json.JsonConvert.DeserializeObject<Rootobject>(sJSON);
Price price = obj.Collegetrips.Select(ct =>
{
var r = ct.tripsdate.Select(td =>
{
var r1 = td.Places.Select(p =>
{
Price itemPrice = p.price.FirstOrDefault();
return itemPrice;
}).FirstOrDefault();
return r1;
}).FirstOrDefault();
return r;
}).FirstOrDefault();
if (price != null)
Console.Write(price.priceAmount);
else
Console.Write("Not Found!");
}
public class Rootobject
{
public Studentinformation StudentInformation { get; set; }
public Collegeinformation CollegeInformation { get; set; }
public Collegetrip[] Collegetrips { get; set; }
}
public class Studentinformation
{
public object rollNumber { get; set; }
public bool isClassLeader { get; set; }
public string result { get; set; }
}
public class Collegeinformation
{
public string[] allClass { get; set; }
public string currencyAccepted { get; set; }
public object[] calendarDates { get; set; }
public string currencyCode { get; set; }
public object collegeCode { get; set; }
public bool hasBulidingFundPrices { get; set; }
public bool hasHostel { get; set; }
public bool hasSecurityFares { get; set; }
}
public class Collegetrip
{
public Tripsdate[] tripsdate { get; set; }
}
public class Tripsdate
{
public string departureTripDate { get; set; }
public Place[] Places { get; set; }
}
public class Place
{
public string destination { get; set; }
public Price[] price { get; set; }
}
public class Price
{
public int priceAmount { get; set; }
}
I use:
http://json2csharp.com/
to get a class representing the Json Object.
public class StudentInformation
{
public object rollNumber { get; set; }
public bool isClassLeader { get; set; }
public string result { get; set; }
}
public class CollegeInformation
{
public List<string> allClass { get; set; }
public string currencyAccepted { get; set; }
public List<object> calendarDates { get; set; }
public string currencyCode { get; set; }
public object collegeCode { get; set; }
public bool hasBulidingFundPrices { get; set; }
public bool hasHostel { get; set; }
public bool hasSecurityFares { get; set; }
}
public class Price
{
public int priceAmount { get; set; }
}
public class Place
{
public string destination { get; set; }
public List<Price> price { get; set; }
}
public class Tripsdate
{
public string departureTripDate { get; set; }
public List<Place> Places { get; set; }
}
public class Collegetrip
{
public List<Tripsdate> tripsdate { get; set; }
}
public class JsonResponse
{
public StudentInformation StudentInformation { get; set; }
public CollegeInformation CollegeInformation { get; set; }
public List<Collegetrip> Collegetrips { get; set; }
}
After that I use Newtonsoft.Json to fill the Class:
using Newtonsoft.Json;
namespace GitRepositoryCreator.Common
{
class JObjects
{
public static string Get(object p_object)
{
return JsonConvert.SerializeObject(p_object);
}
internal static T Get<T>(string p_object)
{
return JsonConvert.DeserializeObject<T>(p_object);
}
}
}
You can call it like that:
JsonResponse jsonClass = JObjects.Get<JsonResponse>(stringJson);
string stringJson = JObjects.Get(jsonClass);
PS:
If your json variable name is no valid C# name you can fix that like this:
public class Exception
{
[JsonProperty(PropertyName = "$id")]
public string id { get; set; }
public object innerException { get; set; }
public string message { get; set; }
public string typeName { get; set; }
public string typeKey { get; set; }
public int errorCode { get; set; }
public int eventId { get; set; }
}

json problems while reading a facebook page

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;
}

Categories