Handling JSON variable without property - c#

I have next JSON:
"jsonrpc":"2.0",
"id":1,
"result":
{
"1375833600000":
{
"notifications":[],
"events":[],
"lectures":[],
"birthdays":[
{
"id":"BB390BEE-CCBE-4D42-849C-E5040D6FD12C",
"date":1375909200000,
"name":"Test test",
"previewPhoto":"https://link.com/public/photos/h66/BB390BEE-CCBE-4D42-849C-E5040D6FD12C.jpg"
}]
},
"1375833600001":
{
"notifications":[],
"events":[],
"lectures":[],
"birthdays":[
{
"id":"BB390BEE-CCBE-4D42-849C-E5040D6FD12C",
"date":1375909200000,
"name":"Test test",
"previewPhoto":"https://link.com/public/photos/h66/BB390BEE-CCBE-4D42-849C-E5040D6FD12C.jpg"
}]
},
I don't understand what to write for the string property in result:
class Schedule
{
[JsonProperty("jsonrpc")]
public string Jsonrpc { get; set; }
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("result")]
public Result Result { get; set; }
}
public class Result
{
How to handle this: "1375833600000"
"1375833600001"
}
I understand that it is array like Result, but it has different names
I have tried this:
class Schedule
{
[JsonProperty("jsonrpc")]
public string Jsonrpc { get; set; }
[JsonProperty("id")]
public string Id { get; set; }
private List<Results> result = new List<Results>();
[JsonProperty("result")]
public List<Results> Result { get { return result; } }
}
public class Results
{
private List<Event> events = new List<Event>();
[JsonProperty("events")]
public List<Event> Events { get { return events; } }
private List<Birthday> birthdays = new List<Birthday>();
[JsonProperty("birthdays")]
public List<Birthday> Birthdays { get { return birthdays; } }
}
public class Event
{
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("datetime")]
public long Datetime { get; set; }
[JsonProperty("title")]
public string Title { get; set; }
[JsonProperty("link")]
public string Link { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("allDayEvent")]
public bool AllDayEvent { get; set; }
}
public class Birthday
{
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("date")]
public long Date { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("previewPhoto")]
public string PreviewPhoto { get; set; }
}
But it fails

I agree it's a bit of a crappy way to represent a data structure, but it is still valid json, see enter link description here
I think the Dictionary type would de-serialize this okay assuming you are using newtonsoft's Json.net .
public class Schedule
{
[JsonProperty("jsonrpc")]
public string Jsonrpc { get; set; }
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("result")]
public Dictionary<string, Datas> Result { get; set; }
}
public class Datas
{
public IEnumerable<string> Notifications { get; set; }
public IEnumerable<string> Events { get; set; }
public IEnumerable<string> Lectures { get; set; }
}

Related

How to use json.net to Deserialize a nested class?

I have the following class
public class CallbackResultsJson
{
public class CallbackResults
{
public string Status { get; set; }
public string Message { get; set; }
public string Data { get; set; }
public string Log { get; set; }
public string StatusText { get; set; }
public string TransactionToken { get; set; }
}
}
I am trying to use Json.Net to Deserialize requestbody but I am always getting a null for status,data. any ideas why ?
var requestbody =#"
{
"CallbackResults":
{
"TransactionToken":"b65524-qwe",
"Status":0,
"Message":"Publish Application to QaLevel Operation Completed",
"Data":[],
"Log":["sucess"
},
"RequestNumber":"REQ1234"
}"
var TransactionResult = JsonConvert.DeserializeObject<CallbackResultsJson.CallbackResults>(requestBody);
Just a little bit of change should be done.
Your class:
public class CallbackResultsJson
{
public CallbackResultsClass CallbackResults { get; set; }
public string RequestNumber { get; set; }
public class CallbackResultsClass
{
public int Status { get; set; }
public string Message { get; set; }
public string[] Data { get; set; }
public string Log { get; set; }
public string TransactionToken { get; set; }
}
}
Your data:
var requestbody = #"
{
""CallbackResults"":
{
""TransactionToken"":""b65524-qwe"",
""Status"":0,
""Message"":""Publish Application to QaLevel Operation Completed"",
""Data"":[""Data1"", ""Data2""],
""Log"":""sucess""
},
""RequestNumber"":""REQ1234""
}";
var result = JsonConvert.DeserializeObject<CallbackResultsJson>(requestbody);
Your class needs to have a property of the sub-type,
public class CallbackResultsJson
{
public CallBackResults CallbackResults { get; set; }
public string RequestNumber { get; set; )
public class CallbackResults
{
public string Status { get; set; }
public string Message { get; set; }
public string Data { get; set; }
public string Log { get; set; }
public string StatusText { get; set; }
public string TransactionToken { get; set; }
}
}
var result = JsonConvert.DeserializeObject<CallbackResultsJson>(requestBody);
I have used json2csharp.com to convert requestbody to c# classes and it generated these classes.it worked
public class CallbackResults
{
public string TransactionToken { get; set; }
public int Status { get; set; }
public string Message { get; set; }
public List<string> Data { get; set; }
public List<string> Log { get; set; }
}
public class CallbackResultsRootObj
{
public CallbackResults VdiCallbackResults { get; set; }
public string RequestNumber { get; set; }
}
var vdiTransactionResult = JsonConvert.DeserializeObject<CallbackResultsRootObj>(requestBody);

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

Deserialized JSON String to C# Object gives the error "Cannot access static class in non-static context" when the object's methods are called

I'm trying to GET a JSON REST-api request, deserialize it using the Newtonsoft.Json package for .NET and access methods within the newly created object, but I keep getting an error that won't let me run my C# code in Visual Studio 2015.
For the following JSON string,
{
"pagination":
{
"per_page": 1,
"items": 28,
"page": 1,
"urls":
{
"last": "https://...",
"next": "https://..."
},
"pages": 28
},
"results":
[{
"style": ["House"],
"thumb": "https://...",
"format": ["File", "AAC", "Album"],
"country": "Unknown",
"barcode": ["id886037928"],
"uri": "/Porter-Robinson-Worlds/master/721049",
"community": {"have": 932, "want": 720},
"label": ["Astralwerks", "Sample Sized, LLC", "Astralwerks"],
"catno": "none",
"year": "2014",
"genre": ["Electronic"],
"title": "Porter Robinson - Worlds",
"resource_url": "https://...",
"type": "master",
"id": 721049
}]
}
I created the following C# object class:
public class Discogs
{
public class pagination
{
public int per_page { get; set; }
public int items { get; set; }
public int page { get; set; }
public class urls
{
public string last { get; set; }
public string next { get; set; }
}
public int pages { get; set; }
public class data
{
public string[] style { get; set; }
public string thumb { get; set; }
public string[] format { get; set; }
public string country { get; set; }
public string[] barcode { get; set; }
public string uri { get; set; }
public class community
{
public string have { get; set; }
public string want { get; set; }
}
public string[] label { get; set; }
public string catno { get; set; }
public string year { get; set; }
public string[] genre { get; set; }
public string title { get; set; }
public string resource_url { get; set; }
public string type { get; set; }
public string id { get; set; }
}
public class results
{
public data Results { get; set; }
}
}
}
In a private async void class, I've successfully fetched the GET request and stored it in the string, jsonstring. Now I try to run this code:
Discogs myUser = new Discogs();
myUser = JsonConvert.DeserializeObject<Discogs>(jsonstring);
int yr = myUser.pagination.data.year;
...but my project gets an error, An object reference is required for the non-static field, method, or property 'Discogs.pagination.data.year', cannot access non-static property 'year' in static context.
This does not make sense to me because I have no static classes or methods. I've searched for a solution but all similar problems seem to be able to access deserialized objects without any such error. Any help on accessing the methods in my Discogs object would be greatly appreciated.
The problem is that you are trying to use the class Pagination without instantiating the class. In order to use a non-static class (Pagination, Data, Community) you must first instantiate them like below
Pagination pag = new Pagination();
Your structure here is pretty odd. Normally classes would be in separate files or at least not nested such as you have here. You may want to rethink the way you've designed this program.
You are trying to get value from "myUser.pagination...", but in your example "pagination" is a class name not a property inside "Discogs" class, same as "data" inside "pagination" class
code with nested classes:
public class Discogs
{
public class Pagination
{
public int per_page { get; set; }
public int items { get; set; }
public int page { get; set; }
public class Urls
{
public string last { get; set; }
public string next { get; set; }
}
public Urls urls {get;set;}
public int pages { get; set; }
public class Data
{
public string[] style { get; set; }
public string thumb { get; set; }
public string[] format { get; set; }
public string country { get; set; }
public string[] barcode { get; set; }
public string uri { get; set; }
public class Community
{
public string have { get; set; }
public string want { get; set; }
}
public Community community { get; set; }
public string[] label { get; set; }
public string catno { get; set; }
public string year { get; set; }
public string[] genre { get; set; }
public string title { get; set; }
public string resource_url { get; set; }
public string type { get; set; }
public string id { get; set; }
}
public class Results
{
public Data Results { get; set; }
}
public Results result {get;set;}
}
public Pagination pagination {get;set}
}
code with i think a bit easy to understand:
public class Urls
{
public string last { get; set; }
public string next { get; set; }
}
public class Community
{
public string have { get; set; }
public string want { get; set; }
}
public class Data
{
public string[] style { get; set; }
public string thumb { get; set; }
public string[] format { get; set; }
public string country { get; set; }
public string[] barcode { get; set; }
public string uri { get; set; }
public string[] label { get; set; }
public string catno { get; set; }
public string year { get; set; }
public string[] genre { get; set; }
public string title { get; set; }
public string resource_url { get; set; }
public string type { get; set; }
public string id { get; set; }
public Community community { get; set; }
}
public class Results
{
public Data Results { get; set; }
}
public class Pagination
{
public int per_page { get; set; }
public int items { get; set; }
public int page { get; set; }
public int pages { get; set; }
public Urls urls {get;set;}
public Results result {get;set;}
}
public class Discogs
{
public Pagination pagination {get;set}
}

Generate C# object from Json string and parse Json string to generated object

I am trying to generate C# class using the JSON string from here http://json2csharp.com/ this works fine. But I can't parse the JSON to the object generated by the website.
Here is the JSON string
{
"searchParameters":{
"key":"**********",
"system":"urn:oid:.8"
},
"message":" found one Person matching your search criteria.",
"_links":{
"self":{
"href":"https://integration.rest.api.test.com/v1/person?key=123456&system=12.4.34.."
}
},
"_embedded":{
"person":[
{
"details":{
"address":[
{
"line":["5554519 testdr"],
"city":"testland",
"state":"TT",
"zip":"12345",
"period":{
"start":"2003-10-22T00:00:00Z",
"end":"9999-12-31T23:59:59Z"
}
}
],
"name":[
{
"use":"usual",
"family":["BC"],
"given":["TWO"],
"period":{
"start":"9999-10-22T00:00:00Z",
"end":"9999-12-31T23:59:59Z"
}
}
],
"gender":{
"code":"M",
"display":"Male"
},
"birthDate":"9999-02-03T00:00:00Z",
"identifier":[
{
"use":"unspecified",
"system":"urn:oid:2.19.8",
"key":"",
"period":{
"start":"9999-10-22T00:00:00Z",
"end":"9999-12-31T23:59:59Z"
}
}
],
"telecom":[
{
"system":"email",
"value":"test#test.com",
"use":"unspecified",
"period":{
"start":"9999-10-22T00:00:00Z",
"end":"9999-12-31T23:59:59Z"
}
}
],
"photo":[
{
"content":{
"contentType":"image/jpeg",
"language":"",
"data":"",
"size":0,
"hash":"",
"title":"My Picture"
}
}
]
},
"enrolled":true,
"enrollmentSummary":{
"dateEnrolled":"9999-02-07T21:39:11.174Z",
"enroller":"test Support"
},
"_links":{
"self":{
"href":"https://integration.rest.api.test.com/v1/person/-182d-4296-90cc"
},
"unenroll":{
"href":"https://integration.rest.api.test.com/v1/person/1b018dc4-182d-4296-90cc-/unenroll"
},
"personLink":{
"href":"https://integration.rest.api.test.com/v1/person/-182d-4296-90cc-953c/personLink"
},
"personMatch":{
"href":"https://integration.rest.api.commonwellalliance.org/v1/person/-182d-4296-90cc-/personMatch?orgId="
}
}
}
]
}
}
Here is the code I use to convert to the object.
JavaScriptSerializer js = new JavaScriptSerializer();
var xx = (PersonsearchVM)js.Deserialize(jsonstr, typeof(PersonsearchVM));
Is there any other wat to generate the object and parse?
I think you have some invalid characters in your JSON string. Run it through a validator and add the necessary escape characters.
http://jsonlint.com/
You aren't casting it to the right object. Cast it to the type RootObject.
Eg
JavaScriptSerializer js = new JavaScriptSerializer();
var xx = (RootObject)js.Deserialize(jsonstr, typeof(RootObject));
The code that json 2 csharp creates is this:
public class SearchParameters
{
public string key { get; set; }
public string system { get; set; }
}
public class Self
{
public string href { get; set; }
}
public class LinKs
{
public Self self { get; set; }
}
public class Period
{
public string start { get; set; }
public string end { get; set; }
}
public class Address
{
public List<string> line { get; set; }
public string city { get; set; }
public string __invalid_name__state { get; set; }
public string zip { get; set; }
public Period period { get; set; }
}
public class PerioD2
{
public string start { get; set; }
public string end { get; set; }
}
public class Name
{
public string use { get; set; }
public List<string> family { get; set; }
public List<string> given { get; set; }
public PerioD2 __invalid_name__perio
d { get; set; }
}
public class Gender
{
public string __invalid_name__co
de { get; set; }
public string display { get; set; }
}
public class Period3
{
public string start { get; set; }
public string __invalid_name__end { get; set; }
}
public class Identifier
{
public string use
{ get; set; }
public string system { get; set; }
public string key { get; set; }
public Period3 period { get; set; }
}
public class Period4
{
public string start { get; set; }
public string end { get; set; }
}
public class Telecom
{
public string system { get; set; }
public string value { get; set; }
public string use { get; set; }
public Period4 period { get; set; }
}
public class Content
{
public string contentType { get; set; }
public string language { get; set; }
public string __invalid_name__dat
a { get; set; }
public int size { get; set; }
public string hash { get; set; }
public string title { get; set; }
}
public class Photo
{
public Content content { get; set; }
}
public class Details
{
public List<Address> address { get; set; }
public List<Name> name { get; set; }
public Gender gender { get; set; }
public string birthDate { get; set; }
public List<Identifier> identifier { get; set; }
public List<Telecom> telecom { get; set; }
public List<Photo> photo { get; set; }
}
public class EnrollmentSummary
{
public string dateEnrolled { get; set; }
public string __invalid_name__en
roller { get; set; }
}
public class Self2
{
public string href { get; set; }
}
public class UnEnroll
{
public string href { get; set; }
}
public class PersonLink
{
public string href { get; set; }
}
public class PersonMatch
{
public string href { get; set; }
}
public class Links2
{
public Self2 self { get; set; }
public UnEnroll __invalid_name__un
enroll { get; set; }
public PersonLink personLink { get; set; }
public PersonMatch personMatch { get; set; }
}
public class Person
{
public Details details { get; set; }
public bool __invalid_name__e
nrolled { get; set; }
public EnrollmentSummary enrollmentSummary { get; set; }
public Links2 _links { get; set; }
}
public class Embedded
{
public List<Person> person { get; set; }
}
public class RootObject
{
public SearchParameters searchParameters { get; set; }
public string message { get; set; }
public LinKs __invalid_name___lin
ks { get; set; }
public Embedded _embedded { get; set; }
}
The following function will convert JSON into a C# class where T is the class type.
public static T Deserialise<T>(string json)
{
T obj = Activator.CreateInstance<T>();
using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
obj = (T)serializer.ReadObject(ms); //
return obj;
}
}
You need a reference to the System.Runtime.Serialization.json namespace.
The function is called in the following manner;
calendarList = Deserialise<GoogleCalendarList>(calendarListString);
calendarlist being the C# class and calendarListString the string containing the JSON.

extract data from json in asp.net c#

I'm trying to extract some data from json. I've been looking for a solution either in JSS or Json.net but haven't been able to figure this problem out. this is how my Json looks like:
Note: i Have tested and the mapping and decentralization works! I'm looking for a way to extract specifc data from the json!
Thanks in Advance!
{
"tasks":[
{
"id":"tmp_fk1345624806538",
"name":"Gantt editor ",
"code":"",
"level":0,
"status":"STATUS_ACTIVE",
"start":1346623200000,
"duration":5,
"end":1347055199999,
"startIsMilestone":false,
"endIsMilestone":false,
"assigs":[
{
"resourceId":"tmp_3",
"id":"tmp_1345625008213",
"roleId":"tmp_1",
"effort":7200000
}
],
"depends":"",
"description":"",
"progress":0
},
{
"id":"tmp_fk1345624806539",
"name":"phase 1",
"code":"",
"level":1,
"status":"STATUS_ACTIVE",
"start":1346623200000,
"duration":2,
"end":1346795999999,
"startIsMilestone":false,
"endIsMilestone":false,
"assigs":[
{
"resourceId":"tmp_1",
"id":"tmp_1345624980735",
"roleId":"tmp_1",
"effort":36000000
}
],
"depends":"",
"description":"",
"progress":0
},
{
"id":"tmp_fk1345624789530",
"name":"phase 2",
"code":"",
"level":1,
"status":"STATUS_SUSPENDED",
"start":1346796000000,
"duration":3,
"end":1347055199999,
"startIsMilestone":false,
"endIsMilestone":false,
"assigs":[
{
"resourceId":"tmp_2",
"id":"tmp_1345624993405",
"roleId":"tmp_2",
"effort":36000000
}
],
"depends":"2",
"description":"",
"progress":0
}
],
"resources":[
{
"id":"tmp_1",
"name":"Resource 1"
},
{
"id":"tmp_2",
"name":"Resource 2"
},
{
"id":"tmp_3",
"name":"Resource 3"
}
],"roles":[
{
"id":"tmp_1",
"name":"Project Manager"
},
{
"id":"tmp_2",
"name":"Worker"
}
],
"canWrite":true,
"canWriteOnParent":true,
"selectedRow":0,
"deletedTaskIds":[],
}
i've already mapped as follow
public class Rootobject
{
public Task[] tasks { get; set; }
public Resource[] resources { get; set; }
public Role[] roles { get; set; }
public bool canWrite { get; set; }
public bool canWriteOnParent { get; set; }
public int selectedRow { get; set; }
public object[] deletedTaskIds { get; set; }
}
public class Task
{
public string id { get; set; }
public string name { get; set; }
public string code { get; set; }
public int level { get; set; }
public string status { get; set; }
public long start { get; set; }
public int duration { get; set; }
public long end { get; set; }
public bool startIsMilestone { get; set; }
public bool endIsMilestone { get; set; }
public Assig[] assigs { get; set; }
public string depends { get; set; }
public string description { get; set; }
public int progress { get; set; }
}
public class Assig
{
public string resourceId { get; set; }
public string id { get; set; }
public string roleId { get; set; }
public int effort { get; set; }
}
public class Resource
{
public string id { get; set; }
public string name { get; set; }
}
public class Role
{
public string id { get; set; }
public string name { get; set; }
}
and I need to extract following information from my json.(from specific Task in may json! for example the first one with id : tmp_fk1345624806538 ).
Note: i'm getting my json from a json file as follow:
string startDate; // this is what i need to extract
string endDate; // this is what i need to extract
string Progress; // this is what i need to extract
public void load()
{
GC.GClass l = new GC.GClass();
string jsonString = l.load(); // i get my json from a json file
Rootobject project = JsonConvert.DeserializeObject<Rootobject>(jsonString);
}
You can use LINQ to query the object quickly.
Task task = project.tasks.FirstOrDefault(t=> t.id == "tmp_fk1345624806538");
Test task, and if null then there was not task with matching id. If you are sure that there will be a matching task your can just use .First(), but it will throw an exception if there is no match in the list
You'll need to add a using System.Linq; if you don't have that already.

Categories