Json.Net serialise collection into named attributes - c#

I am creating a Xamarin app with API calls managed by Refit and other Paul Betts libraries and was looking at serialising a collection of objects into a Json attributed array.
The question I have is how do I serialise the collection of MemberSlot objects in the MemberBooking type, using Json.Net, into the desired Json?
The names of the objects will always be numbers 1 -> 4 but some or all may not be present.
Question
Could I just change the List property in the MemberBooking object to a Dictionary and populate the string key appropriately?
Object heirarchy
public class MemberBookingRequest
{
[JsonProperty("member_booking_request")]
public MemberBooking Booking { get; set; }
}
public class MemberBooking
{
[JsonProperty("course_id")]
public int CourseId { get; set; }
[JsonProperty("date")]
public string TeeDate { get; set; }
[JsonProperty("time")]
public string TeeTime { get; set; }
[JsonProperty("slots")]
public List<MemberSlot> Slots { get; set; }
}
public class MemberSlot
{
[JsonIgnore]
public int Id { get; set; }
[JsonProperty("type")]
public BookingType Type { get; set; }
[JsonProperty("holes")]
public int Holes { get; set; }
[JsonProperty("user_id")]
public int MemberId { get; set; }
}
Current Json
{
"member_booking_request":{
"course_id":1,
"date":"2016-09-29",
"time":"09:00",
"slots":[
{
"type":"Member",
"holes":18,
"user_id":110
},
{
"type":"Member",
"holes":18,
"user_id":111
},
{
"type":"Member",
"holes":18,
"user_id":112
},
{
"type":"Member",
"holes":18,
"user_id":117
]
}
}
}
Desired Json
{
"member_booking_request":{
"course_id":1,
"date":"2016-09-29",
"time":"09:00",
"slots":{
"1":{
"type":"Member",
"holes":18,
"user_id":110
},
"2":{
"type":"Member",
"holes":18,
"user_id":111
},
"3":{
"type":"Member",
"holes":18,
"user_id":112
},
"4":{
"type":"Member",
"holes":18,
"user_id":117
}
}
}
}

You'll have to change the way you create Slots property. Assign MemberSlot.Id as key, MemberSlot itself as value when filling Slots dictionary.
public class MemberBooking
{
[JsonProperty("course_id")]
public int CourseId { get; set; }
[JsonProperty("date")]
public string TeeDate { get; set; }
[JsonProperty("time")]
public string TeeTime { get; set; }
[JsonProperty("slots")]
public Dictionary<int,MemberSlot> Slots { get; set; }
}

This sample will give the your desired json output,using a dictionary
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
namespace jsonconversion
{
public class Program
{
public static void Main(string[] args)
{
Dictionary<int,MemberSlot> slots=new Dictionary<int, MemberSlot>();
MemberSlot slot1 = new MemberSlot() {Id = 1, Holes =2, MemberId = 1};
slots.Add(1,slot1);
MemberBookingRequest mbr = new MemberBookingRequest
{
Booking = new MemberBooking()
{CourseId = 1, TeeDate ="",TeeTime = "",Slots = slots}
};
string jd = JsonConvert.SerializeObject(mbr);
Console.WriteLine(jd);
}
}
public class MemberBookingRequest
{
[JsonProperty("member_booking_request")]
public MemberBooking Booking { get; set; }
}
public class MemberBooking
{
[JsonProperty("course_id")]
public int CourseId { get; set; }
[JsonProperty("date")]
public string TeeDate { get; set; }
[JsonProperty("time")]
public string TeeTime { get; set; }
[JsonProperty("slots")]
public Dictionary<int, MemberSlot> Slots { get; set; }
}
public class MemberSlot
{
[JsonIgnore]
public int Id { get; set; }
[JsonProperty("holes")]
public int Holes { get; set; }
[JsonProperty("user_id")]
public int MemberId { get; set; }
}
}

Related

Deserializing JSON into C# Class with dynamic object [duplicate]

This question already has answers here:
Complicated Json to C# Object Deserialize with classes
(2 answers)
Closed 7 months ago.
I have json being returned from an API. The JSON is formatted as below:
{
"success":true,
"code":200,
"total":2,
"data":{
"1019588":{
"name":"(t) Bob Jones",
"calls":213,
"user_id":"1019588"
},
"1019741":{
"name":"(t) Chris Smith",
"calls":387,
"user_id":"1019741"
}
}
}
I am trying to deserialize into a C# class but I am having issues with the dynamic id for each employee row.
My code:
AgentPeformanceResponse viewModel = JsonSerializer.Deserialize<AgentPeformanceResponse>(result.Result);
public class AgentPeformanceResponse
{
public bool success { get; set; }
public int code { get; set; }
public int total { get; set; }
public Data data { get; set; }
public AgentPeformanceResponse()
{
data = new Data();
}
}
public class Data
{
public Data()
{
PerformanceReponse = new List<PerformanceReponse>();
}
public List<PerformanceReponse> PerformanceReponse { get; set; }
}
public class PerformanceReponse
{
public string name { get; set; }
public int calls { get; set; }
public string user_id { get; set; }
}
How do I handle the dynamic employee ID so that I can deserialize it all into one object?
You should use a Dictionary:
public class AgentPeformanceResponse
{
public bool success { get; set; }
public int code { get; set; }
public int total { get; set; }
public Dictionary<string,PerformanceReponse> data { get; set; }
}
public class PerformanceReponse
{
public string name { get; set; }
public int calls { get; set; }
public string user_id { get; set; }
}
Example:
string json = #"{
""success"":true,
""code"":200,
""total"":2,
""data"":{
""1019588"":{
""name"":""(t) Bob Jones"",
""calls"":213,
""user_id"":""1019588""
},
""1019741"":{
""name"":""(t) Chris Smith"",
""calls"":387,
""user_id"":""1019741""
}
}
}";
var obj = System.Text.Json.JsonSerializer
.Deserialize<AgentPeformanceResponse>(json);
using System;
using System.Collections.Generic;
public class AgentPeformanceResponse
{
public bool success { get; set; }
public int code { get; set; }
public int total { get; set; }
public Dictionary<string, PerformanceReponse> data { get; set; }
}
public class PerformanceReponse
{
public string name { get; set; }
public int calls { get; set; }
public string user_id { get; set; }
}
public class Program
{
public static void Main()
{
var json = "{\"success\":true,\"code\":200,\"total\":2,\"data\":{\"1019588\":{\"name\":\"(t) Bob Jones\",\"calls\":213,\"user_id\":\"1019588\"},\"1019741\":{\"name\":\"(t) Chris Smith\",\"calls\":387,\"user_id\":\"1019741\"}}}";
var result = System.Text.Json.JsonSerializer.Deserialize<AgentPeformanceResponse>(json);
Console.WriteLine(result.code);
Console.WriteLine(result.data["1019741"].name);
}
}
The output will be
200
(t) Chris Smith
Fiddle for you
https://dotnetfiddle.net/lQu2Ln
all code you really need
Dictionary<string, PerformanceReponse> dict = JsonDocument.Parse(json).RootElement
.GetProperty("data").Deserialize<Dictionary<string,PerformanceReponse>>();
//or if you want a list
List<PerformanceReponse> list = data.Select(d=>d.Value).ToList();
or using Newtonsoft.Json
Dictionary<string,PerformanceReponse> dict = JObject.Parse(json)
["data"].ToObject<Dictionary<string,PerformanceReponse>>();
how to use
PerformanceReponse data1019588= dict["1019588"];

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

C# - Json Deserialize - Cannot deserialize the Json Object

I am new to using the Json format with serializing and deserializing, I am using Json.Net.
As a little activity I decided to use the API from a game that I play to retrieve some simple statistics.
However, I am trying to put this Json into classes (created by json2csharp) but I get the exception.
Additional information: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[TornCityAPI.PlayerStatistics.Stats+RootObject]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
and here is the code.
using Microsoft.Win32;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.NetworkInformation;
using System.Windows.Forms;
namespace TornCityAPI
{
public partial class Form_Main : Form
{
// to hold the users api key
private string apiKey;
public string APIKey
{
get { return apiKey; }
set { apiKey = value; }
}
// location in the registry
private string registryLocation = #"HKEY_CURRENT_USER\TornCityAPI\Watch_App";
public string RegistryLocation
{
get { return registryLocation; }
}
// the url which will be used to retrive information
private string apiUrl = "https://api.torn.com/user/?selections=&key=";
public string ApiUrl
{
get { return apiUrl; }
set { apiUrl = value; }
}
// in case of a network disconnect, we could server the previous results instead.
private string previousTornStats;
public string PreviousTronStats
{
get { return previousTornStats; }
set { previousTornStats = value; }
}
public Form_Main()
{
InitializeComponent();
}
private void Form_Main_Load(object sender, EventArgs e)
{
CheckNetworkConnection();
// if the api key does not exists within the registry
if (Registry.GetValue(registryLocation, "Watch_App", null) == null)
{
// ask the user to insert theirs and open the form to allow that
MessageBox.Show("Please enter your torn API key!");
Form_APIKey apiWindow = new Form_APIKey();
apiWindow.ShowDialog(this);
}
// otherwise
else
{
// connect the url with the api key to get the full, working url to get the information
APIKey = (string)Registry.GetValue(registryLocation, "Watch_App", null);
ApiUrl += APIKey;
MessageBox.Show(apiUrl);
}
}
private void timer_UpdateStats_Tick(object sender, EventArgs e)
{
CheckNetworkConnection();
UpdateTornStats();
}
void UpdateTornStats()
{
using (var webClient = new WebClient())
{
var json = new WebClient().DownloadString(ApiUrl);
var list = JsonConvert.DeserializeObject<List<PlayerStatistics.Stats.RootObject>>(json);
Console.WriteLine(list.Count);
}
}
void CheckNetworkConnection()
{
// if they are not connected to the internet
if (NetworkInterface.GetIsNetworkAvailable() == false)
{
Console.WriteLine("You are not connected to the internet!" + "\n" + "Please connect and restart!");
return;
}
}
}
}
Specifically:
void UpdateTornStats()
{
using (var webClient = new WebClient())
{
var json = new WebClient().DownloadString(ApiUrl);
var list = JsonConvert.DeserializeObject<List<PlayerStatistics.Stats.RootObject>>(json);
Console.WriteLine(list.Count);
}
}
Here is the class I try to put it into.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TornCityAPI.PlayerStatistics
{
class Stats
{
public class Life
{
public int current { get; set; }
public int maximum { get; set; }
public int increment { get; set; }
public int interval { get; set; }
public int ticktime { get; set; }
public int fulltime { get; set; }
}
public class Job
{
public string position { get; set; }
public int company_id { get; set; }
public string company_name { get; set; }
}
public class Faction
{
public string position { get; set; }
public int faction_id { get; set; }
public int days_in_faction { get; set; }
public string faction_name { get; set; }
}
public class Married
{
public int spouse_id { get; set; }
public string spouse_name { get; set; }
public int duration { get; set; }
}
public class Icons
{
public string icon6 { get; set; }
public string icon3 { get; set; }
public string icon8 { get; set; }
public string icon27 { get; set; }
public string icon9 { get; set; }
}
public class RootObject
{
public string rank { get; set; }
public int level { get; set; }
public string gender { get; set; }
public string property { get; set; }
public string signup { get; set; }
public int awards { get; set; }
public int friends { get; set; }
public int enemies { get; set; }
public int forum_posts { get; set; }
public int karma { get; set; }
public int age { get; set; }
public string role { get; set; }
public int donator { get; set; }
public int player_id { get; set; }
public string name { get; set; }
public int property_id { get; set; }
public string last_action { get; set; }
public Life life { get; set; }
public List<string> status { get; set; }
public Job job { get; set; }
public Faction faction { get; set; }
public Married married { get; set; }
public Icons icons { get; set; }
}
}
}
I dont really know how to lay this out or what class should be created from the Json. (However I assume its the root as it has references to the other classes)
Finally, here is the Json which is downloaded to a string:
{
"rank": "Reasonable Punchbag",
"level": 22,
"gender": "Male",
"property": "Ranch",
"signup": "2013-08-01 07:59:43",
"awards": 58,
"friends": 2,
"enemies": 2,
"forum_posts": 25,
"karma": 4,
"age": 1234,
"role": "Civilian",
"donator": 1,
"player_id": 1761543,
"name": "GamingAnonymous",
"property_id": 16693,
"last_action": "18 minutes ago",
"life": {
"current": 429,
"maximum": 1072,
"increment": 53,
"interval": 300,
"ticktime": 258,
"fulltime": 3858
},
"status": [
"In hospital for 3 hrs 4 mins - Hospitalized by someone",
""
],
"job": {
"position": "Employee",
"company_id": 61582,
"company_name": "streamTV - hiring 33k man"
},
"faction": {
"position": "Member",
"faction_id": 17845,
"days_in_faction": 268,
"faction_name": "The Watchers"
},
"married": {
"spouse_id": 2024099,
"spouse_name": "Anonymous_Hugo",
"duration": 62
},
"icons": {
"icon6": "Male",
"icon3": "Donator",
"icon8": "Married - To Anonymous_Hugo",
"icon27": "Company - Employee of streamTV - hiring 33k man (Television Network)",
"icon9": "Faction - Member of The Watchers",
"icon15": "Hospital - Hospitalized by someone - 03:04:17 "
}
}
Any help would be greatly appreciated, thanks.
The error message is pretty straightforward. You're trying to deserialize object to List of RootObject.
Use this snippet:
void UpdateTornStats()
{
using (var webClient = new WebClient())
{
var json = new WebClient().DownloadString(ApiUrl);
var list = JsonConvert.DeserializeObject<PlayerStatistics.Stats.RootObject>(json);
Console.WriteLine(list.Count);
}
}

Serializing Json to c# Class throwing error

I have a JSON returning from web like this
{
"data": {
"normal_customer": {
"0": {
"id": 1,
"name": "ALPHY"
}
},
"1": {
"id": 2,
"name": "STEVEN"
}
},
"luxury_customer": {
"3": {
"id": 8,
"name": "DEV"
}
}
}
}
I have created c# classes
public class StandardCustomers
{
public List<CustomersDetails> Customers_Details { get; set; }
}
public class CustomersDetails
{
[JsonProperty("id")]
public int id { get; set; }
[JsonProperty("name")]
public string name { get; set; }
public class LuxuryCustomers
{
public List<CustomersDetails> Customers_Details { get; set; }
}
public class Data
{
public StandardCustomers standard_Customers { get; set; }
public LuxuryCustomers luxury_Customers { get; set; }
}
public class RootObject
{
public Data data { get; set; }
}
}
When I use deserialize the response from the website using below c# code
var result1 = JsonConvert.DeserializeObject<Data>(response);
but result1.luxury_customers contains customerdetails which is null.
As suggested by #hellostone, I have modified to rootdata, then also
result1.luxury_customers contains customerdetails is null.
Any idea how to deserialize to c# class
When we pasted Json to visual studio, it generated classes as below
public class Rootobject
{
public Data data { get; set; }
}
public class Data
{
public Standard_Customers standard_Customers { get; set; }
public Luxury_Customers luxury_Customers { get; set; }
}
public class Standard_Customers
{
public _0 _0 { get; set; }
public _1 _1 { get; set; }
public _2 _2 { get; set; }
public _4 _4 { get; set; }
public _5 _5 { get; set; }
}
public class _0
{
public int id { get; set; }
public string name { get; set; }
}
individual classes are generated in standard customers , can we use list for this
I guess the problem is that index in luxury_customers starting not from zero. Try to use Dictionary<string,CustomersDetails> in LuxuryCustomers instead List<CustomersDetails>.
I've managed to deserialize Json with this classes:
public class CustomersDetails
{
[JsonProperty("id")]
public int id { get; set; }
[JsonProperty("name")]
public string name { get; set; }
}
public class Data
{
public Dictionary<string, CustomersDetails> normal_customer { get; set; }
public Dictionary<string,CustomersDetails> luxury_customer { get; set; }
}
public class RootObject
{
public Data data { get; set; }
}
Deserialization code:
var result = JsonConvert.DeserializeObject<RootObject>(text);
P.S. I've remove one closing bracket after "ALPHY" element, to make Json valid, I hope it was typo and you're getting valid Json.
Your json string doesn't match with your defined classes. Your Json string should look like this if you want to preserve your class structure:
{
"data":{
"standard_Customers":{
"Customers_Details":[
{
"id":1,
"name":"ALPHY"
},
{
"id":2,
"name":"STEVEN"
}
]
},
"luxury_Customers":{
"Customers_Details":[
{
"id":8,
"name":"DEV"
}
]
}
}
}
Pay attention to the square brackets at the "Customers_Details" attribute.
Then the:
var result1 = JsonConvert.DeserializeObject<RootObject>(response);
call, will give you the right object back and it shouldn't be null, when using your class structure:
public class StandardCustomers
{
public List<CustomersDetails> Customers_Details { get; set; }
}
public class CustomersDetails
{
[JsonProperty("id")]
public int id { get; set; }
[JsonProperty("name")]
public string name { get; set; }
}
public class LuxuryCustomers
{
public List<CustomersDetails> Customers_Details { get; set; }
}
public class Data
{
public StandardCustomers standard_Customers { get; set; }
public LuxuryCustomers luxury_Customers { get; set; }
}
public class RootObject
{
public Data data { get; set; }
}

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