Json Deserialize Exception - c#

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.

Related

Deserialize Complex/Branched JSON and accessing branches

I have a JSON response which i generated a model from. the JSON data has various branches with data as shown below.
{
"error": false,
"result": {
"customers": [
{
"district": null,
"feeder": "XXXXXXXXXXX",
"feeder_code": "XXXXXXXXXXX",
"transformer": "XXXXXXXXXXX",
"dss_code": "XXXXXXXXX",
"database_match": "XXXXXXXXXXX",
"accountnumber": "XXXXXXXXXXX",
"meterno": "XXXXXXXXXXX",
"oldaccountnumber": "XXXXXXXXXXX",
"odoo_account_number": "XXXXXXXXXXX",
"customername": "XXXXXXXXXXX",
"address": "XXXXXXXXXXX",
"phone": "",
"tarrif": "XXX",
"tariff_category": "NON-MD",
"service_band": "C ",
"status": "Active",
"status_period": "MAY",
"payment_status": null,
"arrears": "29431.78",
"long_x": "7.0385020000",
"lat_y": "5.4909420000",
"transactional_details": {
"queryresult": {
"responseMessage": "success",
"customer": {
"accountNumber": "XXXXXXXXXXX",
"meterNumber": "XXXXXXXXXXX",
"phoneNumber": "",
"lastName": "XXXXXXXXXXX",
"address": "XXXXXXXXXXX",
"city": "XXXXXXXXXXX",
"district": "Owerri",
"userCategory": "NON-MD",
"customerType": "metered",
"paymentPlan": "Prepaid",
"vat": 0,
"tariffCode": "R2SC-NMD",
"tariffRate": 52.6,
"arrearsBalance": 0,
"billedAmount": 0,
"billedDate": null,
"lastPayDate": "2021-09-21 12:16:46",
"lastpayment": {
"transactionRef": "88099064",
"units": 0,
"transactionDate": "JXXXXXXXXXXX",
"transactionId": "XXXXXXXXXXX",
"transactionBookId": 0,
"amountPaid": 1000,
"mscPaid": 0,
"invoiceNumber": "17289583"
}
},
"responseCode": 200,
"status": "true"
},
"status": true
}
}
],
"row_count": 2
}
}
I have various branches in this JSON response which i need to use. i generated a model class from this JSON as shown below
// Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
public class Customer
{
public object district { get; set; }
public string feeder { get; set; }
public string feeder_code { get; set; }
public string transformer { get; set; }
public string dss_code { get; set; }
public string database_match { get; set; }
public string accountnumber { get; set; }
public string meterno { get; set; }
public string oldaccountnumber { get; set; }
public string odoo_account_number { get; set; }
public string customername { get; set; }
public string address { get; set; }
public string phone { get; set; }
public string tarrif { get; set; }
public string tariff_category { get; set; }
public string service_band { get; set; }
public string status { get; set; }
public string status_period { get; set; }
public object payment_status { get; set; }
public string arrears { get; set; }
public string long_x { get; set; }
public string lat_y { get; set; }
public TransactionalDetails transactional_details { get; set; }
}
public class Customer2
{
public string accountNumber { get; set; }
public string meterNumber { get; set; }
public string phoneNumber { get; set; }
public string lastName { get; set; }
public string address { get; set; }
public string city { get; set; }
public string district { get; set; }
public string userCategory { get; set; }
public string customerType { get; set; }
public string paymentPlan { get; set; }
public int vat { get; set; }
public string tariffCode { get; set; }
public double tariffRate { get; set; }
public int arrearsBalance { get; set; }
public int billedAmount { get; set; }
public object billedDate { get; set; }
public string lastPayDate { get; set; }
public Lastpayment lastpayment { get; set; }
}
public class Lastpayment
{
public string transactionRef { get; set; }
public int units { get; set; }
public string transactionDate { get; set; }
public string transactionId { get; set; }
public int transactionBookId { get; set; }
public int amountPaid { get; set; }
public int mscPaid { get; set; }
public string invoiceNumber { get; set; }
}
public class Queryresult
{
public string responseMessage { get; set; }
public Customer customer { get; set; }
public int responseCode { get; set; }
public string status { get; set; }
}
public class Result
{
public ObservableCollection<Customer> customers { get; set; }
public int row_count { get; set; }
}
public class Root
{
public bool error { get; set; }
public Result result { get; set; }
}
public class TransactionalDetails
{
public Queryresult queryresult { get; set; }
public bool status { get; set; }
}
Afterwards i used the C# code to deserialize the JSON as shown below
Root myroot = JsonConvert.DeserializeObject<Root>(readTask);
ObservableCollection<Customer> data = myroot.result.customers;
This works fine, however, i am stuck with just customer Data. I want to be able to get the Transactional details (Customer2) and Lastpayment branches in a collection view. how can i achieve this? Thanks
You can parse your json and read it by linq. ToObject method help you to convert nodes to specific class.
I have taken json text in InputJson variable and then paresed it.
var parsed = JObject.Parse(InputJson);
var innerNodes = JArray.Parse(parsed["result"]["customers"].ToString());
var CustomerList = innerNodes.Select(x => x.ToObject<Customer>()).ToList();
And if you need just some of properties you can use in this way
var CustomerList = innerNodes.Select(x =>
new Customer
{
district = x["district"],
feeder = x["feeder"].ToString(),
transactional_details =x["transactional_details"].ToObject<TransactionalDetails>()
})
.ToList();
If you have different nodes in your object , you can call nodes and check them not be null!
var CustomerList = innerNodes.Select(x => new
{
district = x["district"],
feeder = x["feeder"].ToString(),
transactional_details =x["transactional_details"]?.ToObject<TransactionalDetails>(),
Lastpayment = x["transactional_details"]?["queryresult"]?["customer"]?["lastpayment"]?.ToObject<Lastpayment>(),
billedAmount = x["transactional_details"]?["queryresult"]?["customer"]?["billedAmount"] ?.ToString()
}).ToList();
Customers is an array object so you must iterate through this array.
For example this would work:
Root myroot = JsonConvert.DeserializeObject<Root>(json);
myroot.result.customers.ToList().ForEach(c =>
{
Console.WriteLine(c.transactional_details.queryresult.customer.lastpayment.amountPaid);
});
Looking at Locals in vs debugger for
var customers = myroot.result.customers.ToList();
we get this:
fix Queryresult class by changing Customer to Customer2
public class Queryresult
{
public string responseMessage { get; set; }
public Customer2 customer { get; set; }
public int responseCode { get; set; }
public string status { get; set; }
}
now you can get a lastpayment
Root myroot = JsonConvert.DeserializeObject<Root>(readTask);
LastPayment lastPayment = myroot.result.customers
.Select(c=>c.transactional_details.queryresult.customer.lastpayment).FirstOrDefault();
how to use
var amountPaid = lastPayment.amountPaid; //1000
var invoiceNumber = lastPayment.invoiceNumber; //17289583

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/

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

C# - How convert json string to class

How can I convert my json-string to class
this is my json
{
"$id": "1",
"Result": {
"$id": "2",
"dateTime": 23821964,
"list": [{
"$id": "3",
"UserId": 302,
"UID": "302_UID",
"Title": "شیدکو",
"Sender": "شیدکو",
"Answer": "",
"Comment": "test 2",
"ProductTitle": null,
"CommentId": 77,
"Logo": "http://example.com/Commercial/User/302/Logo/tmpF0BF.jpg",
"Date": 24302057,
"AnswerDate": -2123661683,
"AnswerEdit": false,
"CommentEdit": false,
"ForfeitCount": 0,
"RewardCount": 0,
"ThisCountReport": 2,
"Reported": [{
"$id": "4",
"BlockerId": 355,
"Title": "محتوای غیر اخلاقی",
"Date": -19527396,
"ForfeitCount": 0,
"RewardCount": 0
}, {
"$id": "5",
"BlockerId": 355,
"Title": "محتوای غیر مرتبط",
"Date": -19527382,
"ForfeitCount": 0,
"RewardCount": 0
}],
"Gem": 0
}, {
"$id": "6",
"UserId": 302,
"UID": "302_UID",
"Title": "شیدکو",
"Sender": "شیدکو",
"Answer": "",
"Comment": "test 2",
"ProductTitle": null,
"CommentId": 77,
"Logo": "http://example.com/Commercial/User/302/Logo/tmpF0BF.jpg",
"Date": 24302057,
"AnswerDate": -2123661683,
"AnswerEdit": false,
"CommentEdit": false
}]
},
"StatusCode": "Created",
"Description": null
}
And I do these step, but nothing happens
JObject json1 = JObject.Parse(strMyJson);
_CommentAdmindto flight = Newtonsoft.Json.JsonConvert.DeserializeObject<_CommentAdmindto>(json1.ToString());
_CommentAdmindto deserializedProduct = JsonConvert.DeserializeObject<_CommentAdmindto>(json);
_CommentAdmindto deserializedProduct1 = ConvertJsonToClass<_CommentAdmindto>(strMyJson);
JsonSerializer serializer = new JsonSerializer();
_CommentAdmindto p = (_CommentAdmindto)serializer.Deserialize(new JTokenReader(strMyJson), typeof(_CommentAdmindto));
And here is my class and function:
public static T ConvertJsonToClass<T>( string json)
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
return serializer.Deserialize<T>(json);
}
}
public class _CommentAdmindto
{
public long dateTime { get; set; }
public IQueryable<CommentDtoAdmin> list { get; set; }
}
public class CommentDtoAdmin
{
public long UserId { get; set; }
public string UID { get; set; }
public string Title { get; set; }
public string Sender { get; set; }
public string Answer { get; set; }
public string Comment { get; set; }
public string ProductTitle { get; set; }
public long CommentId { get; set; }
public string Logo { get; set; }
public long Date { get; set; }
public long AnswerDate { get; set; }
public bool AnswerEdit { get; set; }
public bool CommentEdit { get; set; }
}
Your model should be similar to this (For invalid c# names, you can use JsonProperty attribute) :
public class Reported
{
[JsonProperty("$id")]
public string id { get; set; }
public int BlockerId { get; set; }
public string Title { get; set; }
public int Date { get; set; }
public int ForfeitCount { get; set; }
public int RewardCount { get; set; }
}
public class List
{
[JsonProperty("$id")]
public string id { get; set; }
public int UserId { get; set; }
public string UID { get; set; }
public string Title { get; set; }
public string Sender { get; set; }
public string Answer { get; set; }
public string Comment { get; set; }
public object ProductTitle { get; set; }
public int CommentId { get; set; }
public string Logo { get; set; }
public int Date { get; set; }
public int AnswerDate { get; set; }
public bool AnswerEdit { get; set; }
public bool CommentEdit { get; set; }
public int ForfeitCount { get; set; }
public int RewardCount { get; set; }
public int ThisCountReport { get; set; }
public List<Reported> Reported { get; set; }
public int Gem { get; set; }
}
public class Result
{
[JsonProperty("$id")]
public string id { get; set; }
public int dateTime { get; set; }
public List<List> list { get; set; }
}
public class RootObject
{
[JsonProperty("$id")]
public string id { get; set; }
public Result Result { get; set; }
public string StatusCode { get; set; }
public object Description { get; set; }
}
Now you can deserialize as
var result = JsonConvert.DeserializeObject<RootObject>(jsonstring);
BTW: http://json2csharp.com/ can help to guess your model when working with json.
You seem to be trying to deserialize in a lot of different ways but you don't have a full structure to actually match the json. You miss the outer class (representing the full object) and at least Newtonsoft.Json cannot deserialize to an IQueryable so I changed that to IEnumerable.
string strMyJson = "{\"$id\":\"1\",\"Result\":{\"$id\":\"2\",\"dateTime\":23826985,\"list\":[{\"$id\":\"3\",\"UserId\":302,\"UID\":\"302_UID\",\"Title\":\"شیدکو\",\"Sender\":\"شیدکو\",\"Answer\":\"\",\"Comment\":\"test 2\",\"ProductTitle\":null,\"CommentId\":77,\"Logo\":\"http://www.domain.com/Commercial/User/302/Logo/tmpF0BF.jpg\",\"Date\":24307078,\"AnswerDate\":-2123656662,\"AnswerEdit\":false,\"CommentEdit\":false,\"ForfeitCount\":0,\"RewardCount\":0,\"ThisCountReport\":2,\"Reported\":[{\"$id\":\"4\",\"BlockerId\":355,\"Title\":\"محتوای غیر اخلاقی\",\"Date\":-19527396,\"ForfeitCount\":0,\"RewardCount\":0},{\"$id\":\"5\",\"BlockerId\":355,\"Title\":\"محتوای غیر مرتبط\",\"Date\":-19527382,\"ForfeitCount\":0,\"RewardCount\":0}],\"Gem\":0},{\"$id\":\"6\",\"UserId\":302,\"UID\":\"302_UID\",\"Title\":\"شیدکو\",\"Sender\":\"شیدکو\",\"Answer\":\"\",\"Comment\":\"test 2\",\"ProductTitle\":null,\"CommentId\":77,\"Logo\":\"http://www.domain.com/Commercial/User/302/Logo/tmpF0BF.jpg\",\"Date\":24307078,\"AnswerDate\":-2123656662,\"AnswerEdit\":false,\"CommentEdit\":false}],\"StatusCode\":\"Created\",\"Description\":null}}";
var result = JsonConvert.DeserializeObject<Wrapper>(strMyJson);
with classes looking like this:
public class Wrapper
{
public _CommentAdmindto Result { get; set; }
}
public class _CommentAdmindto
{
public long dateTime { get; set; }
public IEnumerable<CommentDtoAdmin> list { get; set; }
}
CommentDtoAdmin is looking the same.
Though I must say that this only helps you with the deserialization.
Firstly, the $id" properties are synthetic properties added by Json.NET to track and preserve multiple references to the same object. For details, see PreserveReferencesHandling setting.
Thus, if you temporarily remove the "$id" properties, you can upload your JSON to http://json2csharp.com/ and get the following data model:
public class Reported
{
public int BlockerId { get; set; }
public string Title { get; set; }
public int Date { get; set; }
public int ForfeitCount { get; set; }
public int RewardCount { get; set; }
}
public class CommentDtoAdmin
{
public int UserId { get; set; }
public string UID { get; set; }
public string Title { get; set; }
public string Sender { get; set; }
public string Answer { get; set; }
public string Comment { get; set; }
public object ProductTitle { get; set; }
public int CommentId { get; set; }
public string Logo { get; set; }
public int Date { get; set; }
public int AnswerDate { get; set; }
public bool AnswerEdit { get; set; }
public bool CommentEdit { get; set; }
public int ForfeitCount { get; set; }
public int RewardCount { get; set; }
public int ThisCountReport { get; set; }
public List<Reported> Reported { get; set; }
public int Gem { get; set; }
}
public class Result
{
public int dateTime { get; set; }
public List<CommentDtoAdmin> list { get; set; }
}
public class RootObject
{
public Result Result { get; set; }
public string StatusCode { get; set; }
public string Description { get; set; }
}
I then modified the returned model as follows:
I used the name CommentDtoAdmin for the list type.
I set the type of the Description property to string.
Now your JSON can be deserialized and re-serialized as follows:
var settings = new JsonSerializerSettings
{
PreserveReferencesHandling = PreserveReferencesHandling.Objects,
};
var root = JsonConvert.DeserializeObject<RootObject>(json1, settings);
var json2 = JsonConvert.SerializeObject(root, Formatting.Indented, settings);
Note that Json.NET has no built-in logic for deserializing the interface IQueryable<T> to a concrete type, so I had to leave the property as public List<CommentDtoAdmin> list { get; set; }. You can always generate a queryable from the list using AsQueryable():
var queryable = root.Result.list.AsQueryable();
Sample fiddle.
I think you json string does not have correct syntax. It looks like a ']' (end of Array) and a final '}' is missing.
That's what the Visual Studio editor told me when making a json file out of your string after removing all the '\'

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