How To Parse JsonObject in C# - c#

I am trying to Parse json Object below but i dont know how to do this Because Of "lecturer" in json Object ?? i dont know how i can manage "lecturer" their is another Object in Json But in data[0] its a object and at data[1] it is a flag or Boolean . this thing made me confused . Any Idea how i can achieve this ???
{
"result": "Success",
"data": [
{
"student_course_id": "82",
"student_id": "30",
"term_course_id": "18",
"section_id": "3",
"term_id": "12",
"course_id": "15",
"credit_hours": "26",
"is_elective": "Elective",
"is_practical": "0",
"teacher_id": "10",
"program_id": "5",
"course_code": "E2",
"course_title": "English 2",
"lecturer": {
"fname": "Ali",
"lname": "farooq",
"phone": "1234567890",
"email": "farooq#teacher.com",
"thumb": "../photos/thumb/1391515491.png"
}
},
{
"student_course_id": "83",
"student_id": "30",
"term_course_id": "19",
"section_id": "3",
"term_id": "12",
"course_id": "16",
"credit_hours": "26",
"is_elective": "Elective",
"is_practical": "0",
"teacher_id": "8",
"program_id": "5",
"course_code": "C2",
"course_title": "Culture 2",
"lecturer": false
}
]
}
C# Code
public async static Task<StudentSubjectsClassWithError> StudentSubjectsList()
{
HttpClient client = new HttpClient();
string baseUrl = getBaseUrl();
try
{
string flickrResult = await client.GetStringAsync(baseUrl);
StudentSubjectsClassWithError studentSubjectsResult = new StudentSubjectsClassWithError();
try
{
StudentSubjectsJson apiData =
JsonConvert.DeserializeObject<StudentSubjectsJson>(flickrResult);
List<StudentSubjectsClass> mStudentSubjectsList = new List<StudentSubjectsClass>();
if (apiData.data != null && apiData.result == "Success")
{
studentSubjectsResult.message = "";
studentSubjectsResult.result = apiData.result;
foreach (StudentSubjectsJsonItem data in apiData.data)
{
StudentSubjectsClass studentSubjects = new StudentSubjectsClass();
studentSubjects.student_course_id = data.student_course_id;
studentSubjects.student_id = data.student_id;
studentSubjects.term_course_id = data.term_course_id;
studentSubjects.section_id = data.section_id;
studentSubjects.term_id = data.term_id;
studentSubjects.course_id = data.course_id;
studentSubjects.credit_hours = data.credit_hours;
studentSubjects.is_elective = data.is_elective;
studentSubjects.is_practical = data.is_practical;
studentSubjects.program_id = data.program_id;
studentSubjects.course_code = data.course_code;
studentSubjects.course_title = data.course_title;
//// studentSubjects.lecturer ?????
mStudentSubjectsList.Add(studentSubjects);
}
}
else
{
studentSubjectsResult.result = apiData.result;
studentSubjectsResult.message = "No records found.";
}
studentSubjectsResult.studentSubjectsList = mStudentSubjectsList;
return studentSubjectsResult;
}
catch (JsonSerializationException)
{
try
{
StudentSubjectsErrorJson apiData =
JsonConvert.DeserializeObject<StudentSubjectsErrorJson>(flickrResult);
studentSubjectsResult.result = apiData.result;
studentSubjectsResult.message = apiData.data;
studentSubjectsResult.studentSubjectsList = null;
return studentSubjectsResult;
}
catch (JsonSerializationException)
{
}
}
return null;
}
catch (Exception)
{
return null;
// MessageBox.Show("Internet Connection Problem");
}
}

I am using Visual Studio 2012 and when I want to turn a Json string into a C# class object, I copy the Json string and
-> Click Edit
-> Click Paste Special
-> Click Paste JSON as Classes
or you can use the great online tool by Jonathan Keith http://json2csharp.com/
using json2csharp i got this class from your json
public class Datum
{
public string student_course_id { get; set; }
public string student_id { get; set; }
public string term_course_id { get; set; }
public string section_id { get; set; }
public string term_id { get; set; }
public string course_id { get; set; }
public string credit_hours { get; set; }
public string is_elective { get; set; }
public string is_practical { get; set; }
public string teacher_id { get; set; }
public string program_id { get; set; }
public string course_code { get; set; }
public string course_title { get; set; }
public object lecturer { get; set; }
}
public class RootObject
{
public string result { get; set; }
public List<Datum> data { get; set; }
}
Edit
I also noticed that your data array has the lecturer as an object, the second data has lecturer as a bool. You can fix this by simply not including lecturer if it doesn't exist. That would change the classes to this:
public class Lecturer
{
public string fname { get; set; }
public string lname { get; set; }
public string phone { get; set; }
public string email { get; set; }
public string thumb { get; set; }
}
public class Datum
{
public string student_course_id { get; set; }
public string student_id { get; set; }
public string term_course_id { get; set; }
public string section_id { get; set; }
public string term_id { get; set; }
public string course_id { get; set; }
public string credit_hours { get; set; }
public string is_elective { get; set; }
public string is_practical { get; set; }
public string teacher_id { get; set; }
public string program_id { get; set; }
public string course_code { get; set; }
public string course_title { get; set; }
public Lecturer lecturer { get; set; }
}
public class RootObject
{
public string result { get; set; }
public List<Datum> data { get; set; }
}

You've got StudentSubjectsJson for the top level, and StudentSubjectsJsonItem for each isntance in the data array.
For the lecturer you need to define StudentSubjectsJsonLecturer and set is as a property of StudentSubjectsJsonItem called lecturer.
eg:
public class StudentSubjectsJsonItem {
//Existing properties
public StudentSubjectsJsonLecturer lecturer {get;set;}
}
public class StudentSubjectsJsonLecturer {
public string fname {get;set;}
public string lname {get;set;}
//And so on...
}

Since you're already copying properties (you shouldn't have to, this is what deserialization is for) you can deserialize your data into a dynamic object (Newtonsoft Json v4+):
dynamic apiData = JsonConvert.DeserializeObject<StudentSubjectsJson>(flickrResult);
and proceed with the rest of the code as you have it, then when you have to deal with `lecturer' check if it's "false" as you normally would:
if (apiData.data[x].lecturer != false){
...
}
disclaimer: I haven't compiled this to try it, it's a suggestion what to try

I recommend you to use a third party json library instead of writing one yourself. Especially this one: click to download
It's a single-file json library.

Related

How to properly process json with an array of images

I'm new to C#, I can't figure out how to parse JSON with an array of images. Everywhere basic examples with one picture.
For example, if JSON is simple:
{
"Rem": 1,
"name": "bandana for girls",
"articul": "18033325",
"Price": "1 332",
"Pict":"https://public/shop/products/28/00/120028/images/174872/174872.932x1242.jpg"
}
Then I create a class:
public class PriceList
{
public string Name { get; set; }
public string Rem { get; set; }
public string Price { get; set; }
public string articul { get; set; }
public string Pict { get; set; }
}
And then I pass it to XAML:
this.BindingContext = JsonConvert.DeserializeObject<IEnumerable<PriceList>>(json);
But how to process if there is an array of pictures in JSON?:
{
"Rem": 1,
"name": "bandana for girls",
"articul": "1805033325",
"Price": "1 332 ",
"Pict": [
"https://wa-data/public/shop/products/28/00/120028/images/174872/174872.932x1242.jpg",
"https://wa-data/public/shop/products/84/08/120884/images/183097/183097.932x1242.jpg"
]
}
I can not find such an example anywhere, tell me kind people how to solve this problem?
you can deserialize both your jsons using
PriceList priceList=JsonConvert.DeserializeObject<PriceList>(json);
the only difference is that for the second json
public string Pict { get; set; }
should be replaced by
public List<string> Pict { get; set; }
if you don't know what json you will get, this class will be working for both
public class PriceList
{
public string Name { get; set; }
public string Rem { get; set; }
public string Price { get; set; }
public string articul { get; set; }
public List<string> Pict { get; set; }
[Newtonsoft.Json.JsonConstructor]
public PriceList(JToken pict)
{
if (pict.Type.ToString() == "Array")
Pict = pict.ToObject<List<string>>();
else
{
Pict = new List<string>();
Pict.Add(pict.ToString());
}
}
public PriceList() {}
}

Error deserializing JSON file in Visual Studio

I am having a difficulty trying to extract data from the following JSON table:
[
{"type":"header","version":"4.8.3","comment":"Export to JSON plugin for PHPMyAdmin"},
{"type":"database","name":"archaism_dictionary"},
{"type":"table","name":"dictionary","database":"archaism_dictionary","data":
[
{"id":"0","word":"wordOne","synonym":null,"definition":"defOne"},
{"id":"1","word":"wortTwo","synonym":null,"definition":"defTwo"}
]
}
]
My goal is to get a string output for each "word" and each "definition". I have the following class which corresponds to the JSON file:
public class Rootobject
{
public Class1[] Property1 { get; set; }
}
public class Class1
{
public string type { get; set; }
public string version { get; set; }
public string comment { get; set; }
public string name { get; set; }
public string database { get; set; }
public Datum[] data { get; set; }
}
public class Datum
{
public string id { get; set; }
public string word { get; set; }
public object synonym { get; set; }
public string definition { get; set; }
}
Finally this piece of code is supposed to retrieve the first word from the table in the string result:
var list = JsonConvert.DeserializeObject<List<Dictionary.Rootobject>>(rawJSON);
string result = list[0].Property1[0].data[0].word;
The .Property[0] returns null and the program gives me a null reference exception. Where is my code faulty and how should I accomplish this task? Thank you.
EDIT:
I am not sure whether this can mess up the rawJSON string but I get it like this:
rawJSON = File.ReadAllText(FileSystem.AppDataDirectory + fileName);
# Claudio Valerio provide the right json data.
Based on my test, you could try the code below to get the word in the list.
Json daya:
{
"Property1":[
{"type":"header","version":"4.8.3","comment":"Export to JSON plugin for PHPMyAdmin"},
{"type":"database","name":"archaism_dictionary"},
{"type":"table","name":"dictionary","database":"archaism_dictionary","data":
[
{"id":"0","word":"wordOne","synonym":null,"definition":"defOne"},
{"id":"1","word":"wortTwo","synonym":null,"definition":"defTwo"}
]
}
]
}
Class from JSON data:
public class Rootobject
{
public Property1[] Property1 { get; set; }
}
public class Property1
{
public string type { get; set; }
public string version { get; set; }
public string comment { get; set; }
public string name { get; set; }
public string database { get; set; }
public Datum[] data { get; set; }
}
public class Datum
{
public string id { get; set; }
public string word { get; set; }
public object synonym { get; set; }
public string definition { get; set; }
}
Code:
string rawJSON = #"{
'Property1':[
{'type':'header','version':'4.8.3','comment':'Export to JSON plugin for PHPMyAdmin'},
{'type':'database','name':'archaism_dictionary'},
{'type':'table','name':'dictionary','database':'archaism_dictionary','data':
[
{'id':'0','word':'wordOne','synonym':null,'definition':'defOne'},
{'id':'1','word':'wortTwo','synonym':null,'definition':'defTwo'}
]
}
]
}";
var list = JsonConvert.DeserializeObject<Rootobject>(rawJSON);
string result = list.Property1[2].data[0].word;
It is more likely that your input json is something like this:
[
{"type":"header","version":"4.8.3","comment":"Export to JSON plugin for PHPMyAdmin"},
{"type":"database","name":"archaism_dictionary"},
{"type":"table","name":"dictionary","database":"archaism_dictionary","data":
[
{"id":"0","word":"wordOne","synonym":null,"definition":"defOne"},
{"id":"1","word":"wortTwo","synonym":null,"definition":"defTwo"}
]
Note square brakets, they're important.
If I guessed it right, you'll want to deserialize like this:
var list = JsonConvert.DeserializeObject<List<Class1>>(rawJSON);
string result = list[2].data[0].word;
Note: your original code would work only if your input json were:
{
"Property1":[
{"type":"header","version":"4.8.3","comment":"Export to JSON plugin for PHPMyAdmin"},
{"type":"database","name":"archaism_dictionary"},
{"type":"table","name":"dictionary","database":"archaism_dictionary","data":
[
{"id":"0","word":"wordOne","synonym":null,"definition":"defOne"},
{"id":"1","word":"wortTwo","synonym":null,"definition":"defTwo"}
]
}
]
}
and use
var myRoot = JsonConvert.DeserializeObject<RootObject>(rawJSON);
string result = myRoot.Property1[2].data[0].word;
You need to null handle(json NullValueHandling) below is my code please take a look :
string stringJson = #"{
'Property1':[
{'type':'header','version':'4.8.3','comment':'Export to JSON plugin for PHPMyAdmin'},
{'type':'database','name':'archaism_dictionary'},
{'type':'table','name':'dictionary','database':'archaism_dictionary','data':
[
{'id':'0','word':'wordOne','synonym':null,'definition':'defOne'},
{'id':'1','word':'wortTwo','synonym':null,'definition':'defTwo'}
]
}
]
}";
try
{
var settings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
MissingMemberHandling = MissingMemberHandling.Ignore
};
var list = JsonConvert.DeserializeObject<BaseResponse>(stringJson,settings);
string result = list.Property1[2].data[0].word;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Models :
public class WordData
{
public string id { get; set; }
public string word { get; set; }
public object synonym { get; set; }
public string definition { get; set; }
}
public class PropertyData
{
public string type { get; set; }
public string version { get; set; }
public string comment { get; set; }
public string name { get; set; }
public string database { get; set; }
public List<WordData> data { get; set; }
}
public class BaseResponse
{
public List<PropertyData> Property1 { get; set; }
}
I hope it will help you
Thanks

Convert Json String to C# Object List

I want to convert a json string to a Object list. Please help me. it would be more helpful if done by NewtonJson.
I tried, but its not working. I dont want all the values of that json. just which are mentioned in the MatrixModel
This is a Object
public class MatrixModel
{
public string S1 { get; set; }
public string S2 { get; set; }
public string S3 { get; set; }
public string S4 { get; set; }
public string S5 { get; set; }
public string S6 { get; set; }
public string S7 { get; set; }
public string S8 { get; set; }
public string S9 { get; set; }
public string S10 { get; set; }
public int ScoreIfNoMatch { get; set; }
}
This is the Json String
"[
{
"Question": {
"QuestionId": 49,
"QuestionText": "Whats your name?",
"TypeId": 1,
"TypeName": "MCQ",
"Model": {
"options": [
{
"text": "Rahul",
"selectedMarks": "0"
},
{
"text": "Pratik",
"selectedMarks": "9"
},
{
"text": "Rohit",
"selectedMarks": "0"
}
],
"maxOptions": 10,
"minOptions": 0,
"isAnswerRequired": true,
"selectedOption": "1",
"answerText": "",
"isRangeType": false,
"from": "",
"to": "",
"mins": "02",
"secs": "04"
}
},
"CheckType": "",
"S1": "",
"S2": "",
"S3": "",
"S4": "",
"S5": "",
"S6": "",
"S7": "",
"S8": "",
"S9": "Pratik",
"S10": "",
"ScoreIfNoMatch": "2"
},
{
"Question": {
"QuestionId": 51,
"QuestionText": "Are you smart?",
"TypeId": 3,
"TypeName": "True-False",
"Model": {
"options": [
{
"text": "True",
"selectedMarks": "7"
},
{
"text": "False",
"selectedMarks": "0"
}
],
"maxOptions": 10,
"minOptions": 0,
"isAnswerRequired": false,
"selectedOption": "3",
"answerText": "",
"isRangeType": false,
"from": "",
"to": "",
"mins": "01",
"secs": "04"
}
},
"CheckType": "",
"S1": "",
"S2": "",
"S3": "",
"S4": "",
"S5": "",
"S6": "",
"S7": "True",
"S8": "",
"S9": "",
"S10": "",
"ScoreIfNoMatch": "2"
}
]"
You can use json2csharp.com to Convert your json to object model
Go to json2csharp.com
Past your JSON in the Box.
Clik on Generate.
You will get C# Code for your object model
Deserialize by var model = JsonConvert.DeserializeObject<RootObject>(json); using NewtonJson
Here, It will generate something like this:
public class MatrixModel
{
public class Option
{
public string text { get; set; }
public string selectedMarks { get; set; }
}
public class Model
{
public List<Option> options { get; set; }
public int maxOptions { get; set; }
public int minOptions { get; set; }
public bool isAnswerRequired { get; set; }
public string selectedOption { get; set; }
public string answerText { get; set; }
public bool isRangeType { get; set; }
public string from { get; set; }
public string to { get; set; }
public string mins { get; set; }
public string secs { get; set; }
}
public class Question
{
public int QuestionId { get; set; }
public string QuestionText { get; set; }
public int TypeId { get; set; }
public string TypeName { get; set; }
public Model Model { get; set; }
}
public class RootObject
{
public Question Question { get; set; }
public string CheckType { get; set; }
public string S1 { get; set; }
public string S2 { get; set; }
public string S3 { get; set; }
public string S4 { get; set; }
public string S5 { get; set; }
public string S6 { get; set; }
public string S7 { get; set; }
public string S8 { get; set; }
public string S9 { get; set; }
public string S10 { get; set; }
public string ScoreIfNoMatch { get; set; }
}
}
Then you can deserialize as:
var model = JsonConvert.DeserializeObject<List<MatrixModel.RootObject>>(json);
public static class Helper
{
public static string AsJsonList<T>(List<T> tt)
{
return new JavaScriptSerializer().Serialize(tt);
}
public static string AsJson<T>(T t)
{
return new JavaScriptSerializer().Serialize(t);
}
public static List<T> AsObjectList<T>(string tt)
{
return new JavaScriptSerializer().Deserialize<List<T>>(tt);
}
public static T AsObject<T>(string t)
{
return new JavaScriptSerializer().Deserialize<T>(t);
}
}
using dynamic variable in C# is the simplest.
Newtonsoft.Json.Linq has class JValue that can be used. Below is a sample code which displays Question id and text from the JSON string you have.
string jsonString = "[{\"Question\":{\"QuestionId\":49,\"QuestionText\":\"Whats your name?\",\"TypeId\":1,\"TypeName\":\"MCQ\",\"Model\":{\"options\":[{\"text\":\"Rahul\",\"selectedMarks\":\"0\"},{\"text\":\"Pratik\",\"selectedMarks\":\"9\"},{\"text\":\"Rohit\",\"selectedMarks\":\"0\"}],\"maxOptions\":10,\"minOptions\":0,\"isAnswerRequired\":true,\"selectedOption\":\"1\",\"answerText\":\"\",\"isRangeType\":false,\"from\":\"\",\"to\":\"\",\"mins\":\"02\",\"secs\":\"04\"}},\"CheckType\":\"\",\"S1\":\"\",\"S2\":\"\",\"S3\":\"\",\"S4\":\"\",\"S5\":\"\",\"S6\":\"\",\"S7\":\"\",\"S8\":\"\",\"S9\":\"Pratik\",\"S10\":\"\",\"ScoreIfNoMatch\":\"2\"},{\"Question\":{\"QuestionId\":51,\"QuestionText\":\"Are you smart?\",\"TypeId\":3,\"TypeName\":\"True-False\",\"Model\":{\"options\":[{\"text\":\"True\",\"selectedMarks\":\"7\"},{\"text\":\"False\",\"selectedMarks\":\"0\"}],\"maxOptions\":10,\"minOptions\":0,\"isAnswerRequired\":false,\"selectedOption\":\"3\",\"answerText\":\"\",\"isRangeType\":false,\"from\":\"\",\"to\":\"\",\"mins\":\"01\",\"secs\":\"04\"}},\"CheckType\":\"\",\"S1\":\"\",\"S2\":\"\",\"S3\":\"\",\"S4\":\"\",\"S5\":\"\",\"S6\":\"\",\"S7\":\"True\",\"S8\":\"\",\"S9\":\"\",\"S10\":\"\",\"ScoreIfNoMatch\":\"2\"}]";
dynamic myObject = JValue.Parse(jsonString);
foreach (dynamic questions in myObject)
{
Console.WriteLine(questions.Question.QuestionId + "." + questions.Question.QuestionText.ToString());
}
Console.Read();
Output from the code =>
Please make sure that all properties are both the getter and setter. In case, any property is getter only, it will cause the reverting the List to original data as the JSON string is typed.
Please refer to the following code snippet for the same:
Model:
public class Person
{
public int ID { get; set; }
// following 2 lines are cause of error
//public string Name { get { return string.Format("{0} {1}", First, Last); } }
//public string Country { get { return Countries[CountryID]; } }
public int CountryID { get; set; }
public bool Active { get; set; }
public string First { get; set; }
public string Last { get; set; }
public DateTime Hired { get; set; }
}
public class ModelObj
{
public string Str { get; set; }
public List<Person> Persons { get; set; }
}
Controller:
[HttpPost]
public ActionResult Index(FormCollection collection)
{
var data = new ModelObj();
data.Str = (string)collection.GetValue("Str").ConvertTo(typeof(string));
var personsString = (string)collection.GetValue("Persons").ConvertTo(typeof(string));
using (var textReader = new StringReader(personsString))
{
using (var reader = new JsonTextReader(textReader))
{
data.Persons = new JsonSerializer().Deserialize(reader, typeof(List<Person>)) as List<Person>;
}
}
return View(data);
}
If there is no explicit need for a class (model), you can also use dynamic
List<dynamic> models = JsonConvert.DeserializeObject<List<dynamic>>(jsonString);
And then use dot to access whatever fields you need
models[0].MyField
Try to change type of ScoreIfNoMatch, like this:
public class MatrixModel
{
public string S1 { get; set; }
public string S2 { get; set; }
public string S3 { get; set; }
public string S4 { get; set; }
public string S5 { get; set; }
public string S6 { get; set; }
public string S7 { get; set; }
public string S8 { get; set; }
public string S9 { get; set; }
public string S10 { get; set; }
// the type should be string
public string ScoreIfNoMatch { get; set; }
}
The variables/parameters within the class definition requires { get; set; }
I was using like a variable declaration (stupid of me, because it was working for other scenarios) without
{ get; set; }
Because of which, whatever I send from the JavaScript, it was not being received in the Action method. It was always getting null or empty model.
Once the {get; set;} is added, it worked like charm.
I hope it helps someone who is coming from VB6 style of programming line.

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

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