Put JSON items into a WPF GRID in C# - c#

How to put the items in a JSON string in a WPF grid?
{
"success":"true",
"response":{
"Page":1,
"PageFirst":1,
"PageLast":1,
"PageRecordFirst":1,
"PageRecordLast":2147483647,
"PageSize":2147483647,
"RecordCount":2,
"ResultSet":[
{
"CompanyId":1,
"CompanyName":"Focus",
"ComputedProjectProgressAll":39.000000,
"ComputedProjectProgressCurrent":39.000000,
"ComputedProjectProgressExpected":86.00,
"ComputedTaskCountAll":434,
"ComputedTaskCountCurrent":354,
"CreateDate":"\/Date(1421947846600-0800)\/",
"CreateUserId":1,
"CreateUserName":"MobiCloud Admin",
"CustomerId":1,
"CustomerName":"MobiCloud",
"Description":"Obra 001",
"Id":7,
"IsActive":true,
"ModifyDate":"\/Date(1421947846600-0800)\/",
"ModifyUserId":1,
"ModifyUserName":"MobiCloud Admin",
"Name":"Obra Desenv 001",
"Status":0
},
{
"CompanyId":1,
"CompanyName":"Focus",
"ComputedProjectProgressAll":69.000000,
"ComputedProjectProgressCurrent":69.000000,
"ComputedProjectProgressExpected":100.00,
"ComputedTaskCountAll":199,
"ComputedTaskCountCurrent":199,
"CreateDate":"\/Date(1422298868660-0800)\/",
"CreateUserId":1,
"CreateUserName":"MobiCloud Admin",
"CustomerId":1,
"CustomerName":"MobiCloud",
"Description":"sadasdsad",
"Id":8,
"IsActive":true,
"ModifyDate":"\/Date(1422298868660-0800)\/",
"ModifyUserId":1,
"ModifyUserName":"MobiCloud Admin",
"Name":"Obra Desenv 002",
"Status":0
}
]
}
}

First of all you need to create a c# class equivalent to JSON. use http://json2csharp.com/ to create c# class. Then you need to deserialize your JSON string use JSON.NET from http://json.codeplex.com/. Now you have got all the things setup. Now you can assing these data into WPF controls. I have assigned the response resultset into one datagrid. Refer the below code.
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
LoadData();
}
private void LoadData()
{
string str = File.ReadAllText("1.txt");
RootObject deserializedObject = JsonConvert.DeserializeObject<RootObject>(str);
dgr.ItemsSource = deserializedObject.response.ResultSet;
}
}
public class ResultSet
{
public int CompanyId { get; set; }
public string CompanyName { get; set; }
public double ComputedProjectProgressAll { get; set; }
public double ComputedProjectProgressCurrent { get; set; }
public double ComputedProjectProgressExpected { get; set; }
public int ComputedTaskCountAll { get; set; }
public int ComputedTaskCountCurrent { get; set; }
public DateTime CreateDate { get; set; }
public int CreateUserId { get; set; }
public string CreateUserName { get; set; }
public int CustomerId { get; set; }
public string CustomerName { get; set; }
public string Description { get; set; }
public int Id { get; set; }
public bool IsActive { get; set; }
public DateTime ModifyDate { get; set; }
public int ModifyUserId { get; set; }
public string ModifyUserName { get; set; }
public string Name { get; set; }
public int Status { get; set; }
}
public class Response
{
public int Page { get; set; }
public int PageFirst { get; set; }
public int PageLast { get; set; }
public int PageRecordFirst { get; set; }
public long PageRecordLast { get; set; }
public long PageSize { get; set; }
public int RecordCount { get; set; }
public List<ResultSet> ResultSet { get; set; }
}
public class RootObject
{
public string success { get; set; }
public Response response { get; set; }
}
<Grid>
<DataGrid x:Name="dgr"/>
</Grid>

Related

Accessing Nested Collection View JSON data

I have a nested JSON data to be accessed. The data is structured into nested data which i want to have into one.
I modeled the JSON response into c# model classes
public class Customer1
{
public string 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 TransactionalDetails transactional_details { get; set; }
}
public class Customer2
{
public string accountNumber { get; set; }
public string meterNumber { get; set; }
public string phoneNumber { 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 Customer1 customer1 { get; set; }
public int responseCode { get; set; }
public string status { get; set; }
}
public class Result
{
public ObservableCollection<Customer1> Customer1 { 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; }
}
I also created the following code to access the data using the root.
var data = JsonConvert.DeserializeObject<root>(readTask);
ObservableCollection<Customer1> innerData2 = data.result.Customer1;
My challenge is that i want to have Customer1, Customer2 and last payment data merged into a single collection view.
with what i have done, i can only access customer1 data. how can i access all into a single collection?

Deserialize Json Response with nested objects

I'm expecting this response from the API:
{
"EnterKey":"9876546789039876543567890",
"Id":1441462,
"Category":null,
"job":{
"Id":1020332,
"SortName":"test"
},
"Initiator":null,
"Source":{
"Id":1,
"Description":"data"
},
"BalanceNow":0.0,
"ready":false,
"Others":[
{
"Id":1255080,
"Amount":100.0,
"JobMethod":{
"Id":24,
"Description":"task",
"JobType":{
"Id":1,
"Description":"Other"
}
},
"Notes":null
}
],
"Messages":null,
"Products":[
{
"Tasks":{
"Id":2,
"Description":"Blah..."
},
"Join":null,
"TargetData":{
"PaymentId":1535026,
"WantedNotes":"Looks good",
"Name":"John"
},
"AdminDefinedFee":null,
"Product":"New"
}
]
}
I want to deserialize the above Json Response to get the WantedNotes from TargetData that is inside Products. I wanted it done with Json.NET so i tried doing:
public class datasummary
{
public List<TargetData> Products { get; set; }
}
public class TargetData
{
public string WantedNotes { get; set; }
}
var myresult = JsonConvert.DeserializeObject<datasummary>(jsonresponse);
That don't work. I don't know how that really is done. Can someone please show it's done correct?
Define the class structure like this:
public class Job
{
public int Id { get; set; }
public string SortName { get; set; }
}
public class Source
{
public int Id { get; set; }
public string Description { get; set; }
}
public class JobType
{
public int Id { get; set; }
public string Description { get; set; }
}
public class JobMethod
{
public int Id { get; set; }
public string Description { get; set; }
public JobType JobType { get; set; }
}
public class Others
{
public int Id { get; set; }
public double Amount { get; set; }
public JobMethod JobMethod { get; set; }
public object Notes { get; set; }
}
public class Tasks
{
public int Id { get; set; }
public string Description { get; set; }
}
public class TargetData
{
public int PaymentId { get; set; }
public string WantedNotes { get; set; }
public string Name { get; set; }
}
public class Product
{
public Tasks Tasks { get; set; }
public object Join { get; set; }
public TargetData TargetData { get; set; }
public object AdminDefinedFee { get; set; }
public string Product { get; set; }
}
public class DataDummary
{
public string EnterKey { get; set; }
public int Id { get; set; }
public object Category { get; set; }
public Job job { get; set; }
public object Initiator { get; set; }
public Source Source { get; set; }
public double BalanceNow { get; set; }
public bool ready { get; set; }
public List<Others> Others { get; set; }
public object Messages { get; set; }
public List<Product> Products { get; set; }
}
Then use:
var myresult = JsonConvert.DeserializeObject < DataSummary > (jsonresponse);
When working with json, you can copy all text from the file, add an new class then go to
Edit > Paste Especial > Paste JSON as Classes.
It will do all the work for you
Then you can use
var myresult = JsonConvert.DeserializeObject <DataSummary> (jsonresponse);

Access data in JSON C# Dynamic variable

I am working with processing/consuming some data from: https://ashesescalation-api-tachyon.stardock.net/v1/products/2641/leaderboards/ladder/de5bfc9a-9092-4014-b52e-89151de42646?offset=0&count=2 (which can be opened easily in Firefox to view.)
I am able to access the data in C# by doing this:
data being the json data...
dynamic players = JArray.Parse(data);
var p = players[0];
Console.Write(p.personaName);
However I am having trouble accessing the part in the JSON data: "dataInteger" for example the "totalUnitsKilled."
p.dataInteger[0].totalUnitsKilled
That "p.dataInteger[0].totalUnitsKilled" doesn't work.
How can I access that data in C#?
Thank you very much for your help.
Warren
See image in visual studio 1
See image in visual studio 2
Kinldy take a look at my comment in your question, base on that link you need to use JsonProperty to mapped the key that has special characters and manually named it based on your needs.
Anyways, you can do the following to achieved what you need.
Copy your link to http://json2csharp.com/
Copy the generated Quicktypes and paste it to your code.
Use JsonProperty to indicate attributes on your properties for the names and manually rename properties that contains invalid_name
And DeserializeObject the object.
Here is the code:
Declare the classes from the generated quicktypes.
public class DataInteger
{
[JsonProperty(PropertyName = "totalUnitsKilled ")]
public int totalUnitsKilled { get; set; }
public int totalTitansKilled { get; set; }
public int totalTimePlayed { get; set; }
[JsonProperty(PropertyName = "substrate-TotalGamesPlayed")]
public int SubstrateTotalGamesPlayed { get; set; }
[JsonProperty(PropertyName = "phC-TotalGamesPlayed")]
public int PHCTotalGamesPlayed { get; set; }
public int lastReplayVersion { get; set; }
public int replayUploadedCount { get; set; }
}
public class RootObject
{
public string personaLadderId { get; set; }
public int rank { get; set; }
public string personaId { get; set; }
public string personaName { get; set; }
public string avatarUrl { get; set; }
public string avatarUrlSmall { get; set; }
public string avatarUrlMedium { get; set; }
public string avatarUrlLarge { get; set; }
public string ladderType { get; set; }
public string ladderId { get; set; }
public string seasonId { get; set; }
public int bracketId { get; set; }
public string bracketName { get; set; }
public int rankingScore { get; set; }
public int secondaryScore { get; set; }
public int ruleTypeId { get; set; }
public int wins { get; set; }
public int losses { get; set; }
public int ties { get; set; }
public int tieStreak { get; set; }
public int winStreak { get; set; }
public int lossStreak { get; set; }
public int longestTieStreak { get; set; }
public int longestWinStreak { get; set; }
public int longestLossStreak { get; set; }
public int bracketMaxScore { get; set; }
public int bracketScore { get; set; }
public DateTime updateDate { get; set; }
public int totalMatchesPlayed { get; set; }
public DataInteger dataInteger { get; set; }
}
Call the API (Magic begins here)
var httpClient = new HttpClient();
var link = $#"https://ashesescalation-api-tachyon.stardock.net/v1/products/2641/leaderboards/ladder/de5bfc9a-9092-4014-b52e-89151de42646?offset=0&count=2";
var response = await httpClient.GetAsync(link);
var contents = await response.Content.ReadAsStringAsync();
//deserialized json result object...
dynamic json = JsonConvert.DeserializeObject(contents);
foreach (var item in json)
{
//deserialized again the item
var data = JsonConvert.DeserializeObject<RootObject>(Convert.ToString(item));
//you can now access all the properties including dataInteger.
Console.WriteLine(Convert.ToString(data.dataInteger.totalUnitsKilled));
Console.WriteLine(Convert.ToString(data.dataInteger.totalTitansKilled));
}
Update:
If you don't want to use strongly typed class you can do parsing using JArray
JArray jsonVal = JArray.Parse(contents) as JArray;
dynamic items = jsonVal;
foreach (dynamic item in items)
{
var x = item.dataInteger;
//you can access the fields inside dataInteger.
Console.WriteLine(x["totalUnitsKilled "]);
Console.WriteLine(x["phC-TotalGamesPlayed"]);
Console.WriteLine(x["substrate-TotalGamesPlayed"]);
}
Hope this will help you.
As suggested by other users, there is a space in property name "totalUnitsKilled ", if you change it to "totalUnitsKilled". Below code will work fine:-
Console.WriteLine(p.dataInteger.totalUnitsKilled);
Your JSON string is wrong.
[{"personaLadderId":"371eaf1c-4cfe-4873-af41-56e0cb9fcf91","rank":1,"personaId":"55834d01-13f3-445e-861f-0bc4769d87cc","personaName":"Amelie","avatarUrl":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/fe/fef49e7fa7e1997310d705b2a6158ff8dc1cdfeb.jpg","avatarUrlSmall":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/fe/fef49e7fa7e1997310d705b2a6158ff8dc1cdfeb.jpg","avatarUrlMedium":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/fe/fef49e7fa7e1997310d705b2a6158ff8dc1cdfeb_medium.jpg","avatarUrlLarge":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/fe/fef49e7fa7e1997310d705b2a6158ff8dc1cdfeb_full.jpg","ladderType":"Ranked","ladderId":"de5bfc9a-9092-4014-b52e-89151de42646","seasonId":"fd7dd807-4ac2-40ec-8476-a4b2937f70af","bracketId":0,"bracketName":"Legendary","rankingScore":38,"secondaryScore":2054,"ruleTypeId":1,"wins":374,"losses":32,"ties":0,"tieStreak":0,"winStreak":8,"lossStreak":0,"longestTieStreak":0,"longestWinStreak":61,"longestLossStreak":3,"bracketMaxScore":0,"bracketScore":0,"updateDate":"2018-03-03T14:13:09.647Z","totalMatchesPlayed":406,"dataInteger":{"totalUnitsKilled ":92615,"totalTitansKilled":14,"totalTimePlayed":294676,"substrate-TotalGamesPlayed":127,"phC-TotalGamesPlayed":6,"lastReplayVersion":265301040,"replayUploadedCount":160}},{"personaLadderId":"f0dd3482-f057-44d6-a626-9c9389ad2583","rank":2,"personaId":"b53815ab-d753-4415-9ea6-03a4519c3222","personaName":"Rebellions","avatarUrl":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/b9/b9847c92d44896304cc2d673e1fbe7bc99af7f5b.jpg","avatarUrlSmall":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/b9/b9847c92d44896304cc2d673e1fbe7bc99af7f5b.jpg","avatarUrlMedium":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/b9/b9847c92d44896304cc2d673e1fbe7bc99af7f5b_medium.jpg","avatarUrlLarge":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/b9/b9847c92d44896304cc2d673e1fbe7bc99af7f5b_full.jpg","ladderType":"Ranked","ladderId":"de5bfc9a-9092-4014-b52e-89151de42646","seasonId":"fd7dd807-4ac2-40ec-8476-a4b2937f70af","bracketId":0,"bracketName":"Legendary","rankingScore":38,"secondaryScore":2049,"ruleTypeId":1,"wins":767,"losses":188,"ties":0,"tieStreak":0,"winStreak":3,"lossStreak":0,"longestTieStreak":0,"longestWinStreak":52,"longestLossStreak":6,"bracketMaxScore":0,"bracketScore":0,"updateDate":"2017-10-29T18:03:33.92Z","totalMatchesPlayed":955,"dataInteger":{"totalUnitsKilled ":293274,"totalTitansKilled":88,"totalTimePlayed":924881,"phC-TotalGamesPlayed":4,"substrate-TotalGamesPlayed":350,"lastReplayVersion":250285270,"replayUploadedCount":703}}]
There is a space in your json key name ("totalUnitsKilled ") which is ultimately converted to a variable name.
Correct your JSON key name will fix this issue. There are other keys with error as well.
You can check at http://json2csharp.com/. Wherever it is "invalid_name", key name is wrong.
public class DataInteger
{
public int __invalid_name__totalUnitsKilled { get; set; }
public int totalTitansKilled { get; set; }
public int totalTimePlayed { get; set; }
public int __invalid_name__substrate-TotalGamesPlayed { get; set; }
public int __invalid_name__phC-TotalGamesPlayed { get; set; }
public int lastReplayVersion { get; set; }
public int replayUploadedCount { get; set; }
}
public class RootObject
{
public string personaLadderId { get; set; }
public int rank { get; set; }
public string personaId { get; set; }
public string personaName { get; set; }
public string avatarUrl { get; set; }
public string avatarUrlSmall { get; set; }
public string avatarUrlMedium { get; set; }
public string avatarUrlLarge { get; set; }
public string ladderType { get; set; }
public string ladderId { get; set; }
public string seasonId { get; set; }
public int bracketId { get; set; }
public string bracketName { get; set; }
public int rankingScore { get; set; }
public int secondaryScore { get; set; }
public int ruleTypeId { get; set; }
public int wins { get; set; }
public int losses { get; set; }
public int ties { get; set; }
public int tieStreak { get; set; }
public int winStreak { get; set; }
public int lossStreak { get; set; }
public int longestTieStreak { get; set; }
public int longestWinStreak { get; set; }
public int longestLossStreak { get; set; }
public int bracketMaxScore { get; set; }
public int bracketScore { get; set; }
public DateTime updateDate { get; set; }
public int totalMatchesPlayed { get; set; }
public DataInteger dataInteger { get; set; }
}
You can use JSON.Net attributes to define C# variables related to JSON key names. Check this for more details.
Your new class should look like:
public class DataInteger
{
[JsonProperty(PropertyName = "totalUnitsKilled ")]
public int totalUnitsKilled { get; set; }
public int totalTitansKilled { get; set; }
public int totalTimePlayed { get; set; }
[JsonProperty(PropertyName = "substrate-TotalGamesPlayed")]
public int substrateTotalGamesPlayed { get; set; }
[JsonProperty(PropertyName = "phC-TotalGamesPlayed")]
public int phCTotalGamesPlayed { get; set; }
public int lastReplayVersion { get; set; }
public int replayUploadedCount { get; set; }
}

Convert Json Http request to c# obj

I`m new in programming winodws 8 app , i have a webservice when i try to connect it using httprequest (Using URL with variables), this service return this:
{"d":"{\"sessionid\":\"twzv50okccwvgggeesjje2wa\",\"VersionInfo\":{\"Rel\":0,\"Ver\":0,\"Patch\":0,\"ForceUpdate\":0,\"UpdateType\":0,\"Globals\":{\"MultiSessionsAllowed\":true,\"CommCalcType\":2,\"PriceChangedTimer\":25,\"ValidLotsLocation\":2,\"CustumizeTradeMsg\":false,\"FirstWhiteLabeledOffice\":null,\"DealerTreePriv\":0,\"ClientConnectTimer\":200,\"ClientTimeoutTimer\":500,\"DefaultLots\":0.01,\"WebSecurityID\":\"agagag\",\"ServerGMT\":3}},\"SystemLockInfo\":{\"MinutesRemaining\":0,\"HoursRemaining\":0,\"DaysRemaining\":0,\"Maintanance\":0,\"WillBeLocked\":1},\"FirstWhiteLabel\":\"VertexFX 10\",\"WLID\":\"3\",\"CheckWhiteLabel\":true,\"Password\":\"1444\",\"Username\":\"test\",\"LastTickTime\":\"\/Date(1396307573431)\/\",\"SelectedAccount\":78821860,\"Name\":0,\"ServicePath\":null,\"GWSessionID\":\"56630\",\"IP\":\"Web (212.35.90.211)\",\"SessionDateStart\":\"01/04/2014 02:12:53\",\"CompanyName\":\"Hybrid Solutions\",\"UserId\":6119,\"DemoClient\":\"0\",\"FName\":\"omqrstu\",\"SName\":\"\",\"TName\":\"\",\"LName\":\"\",\"Sms\":null,\"isReadOnly\":\"0\",\"SchSms\":\"2\",\"AlertSms\":\"2\",\"Temp\":null,\"GMTOffset\":\"2\",\"SvrGMT\":\"3\",\"ClientType\":null,\"EnableNews\":\"1\",\"PublicSlideNews\":\"\",\"PrivateSlideNews\":\"Welcome to V 10\",\"DealerTreePriv\":1}"}
i have simple windows app with one button when i click the button i send the url with variables and i got the obj above , i want to use content of this object like UserID in if statement but with no vain i dont know how to use it in C# , can and body help me??
I use this code. I know it has many errors but I need someone guide me.
private void Button_Click(object sender, RoutedEventArgs e)
{
String uriString = "url";
var uri = new Uri(uriString);
var httpWebRequest = HttpWebRequest.Create(uri);
httpWebRequest.BeginGetResponse(new AsyncCallback(OnGettingResponse), httpWebRequest);
}
private void OnGettingResponse(IAsyncResult ar)
{
var outerRoot = JsonConvert.DeserializeObject<OuterRootObject>( json );
var root = JsonConvert.DeserializeObject<RootObject>( outerRoot.d );
MessageBox.Show(root.UserId);
}
This is kind of a nasty situation. What you're getting back is a JSON object with a single property (i.e. d) and that property contains a string of JSON. So you basically need to unwrap the inner JSON from it's envelope. The following classes/code should work (using JSON.NET to do the deserialization).
public class OuterRootObject
{
public string d { get; set; }
}
public class Globals
{
public bool MultiSessionsAllowed { get; set; }
public int CommCalcType { get; set; }
public int PriceChangedTimer { get; set; }
public int ValidLotsLocation { get; set; }
public bool CustumizeTradeMsg { get; set; }
public object FirstWhiteLabeledOffice { get; set; }
public int DealerTreePriv { get; set; }
public int ClientConnectTimer { get; set; }
public int ClientTimeoutTimer { get; set; }
public double DefaultLots { get; set; }
public string WebSecurityID { get; set; }
public int ServerGMT { get; set; }
}
public class VersionInfo
{
public int Rel { get; set; }
public int Ver { get; set; }
public int Patch { get; set; }
public int ForceUpdate { get; set; }
public int UpdateType { get; set; }
public Globals Globals { get; set; }
}
public class SystemLockInfo
{
public int MinutesRemaining { get; set; }
public int HoursRemaining { get; set; }
public int DaysRemaining { get; set; }
public int Maintanance { get; set; }
public int WillBeLocked { get; set; }
}
public class RootObject
{
public string sessionid { get; set; }
public VersionInfo VersionInfo { get; set; }
public SystemLockInfo SystemLockInfo { get; set; }
public string FirstWhiteLabel { get; set; }
public string WLID { get; set; }
public bool CheckWhiteLabel { get; set; }
public string Password { get; set; }
public string Username { get; set; }
public DateTime LastTickTime { get; set; }
public int SelectedAccount { get; set; }
public int Name { get; set; }
public object ServicePath { get; set; }
public string GWSessionID { get; set; }
public string IP { get; set; }
public string SessionDateStart { get; set; }
public string CompanyName { get; set; }
public int UserId { get; set; }
public string DemoClient { get; set; }
public string FName { get; set; }
public string SName { get; set; }
public string TName { get; set; }
public string LName { get; set; }
public object Sms { get; set; }
public string isReadOnly { get; set; }
public string SchSms { get; set; }
public string AlertSms { get; set; }
public object Temp { get; set; }
public string GMTOffset { get; set; }
public string SvrGMT { get; set; }
public object ClientType { get; set; }
public string EnableNews { get; set; }
public string PublicSlideNews { get; set; }
public string PrivateSlideNews { get; set; }
public int DealerTreePriv { get; set; }
}
var outerRoot = JsonConvert.DeserializeObject<OuterRootObject>( json );
var root = JsonConvert.DeserializeObject<RootObject>( outerRoot.d );

Json Mapping and serializing in C#

i'm trying to map a json string similar to this in c# to an object.
my purpose is to send it to my cilent side (it's a jquery application)
I was wondering whether i'm doing right ?
{"tasks":[
{
"id":-1,
"name":"Gantt editor",
"code":"",
"level":0,
"status":"STATUS_ACTIVE",
"start":1372608000000,
"duration":21,
"end":1375113599999,
"startIsMilestone":true,
"endIsMilestone":false,
"collapsed":false,
"assigs":[]
},
{
"id":"tmp_fk1372575559620",
"name":"release",
"code":"",
"level":1,
"status":"STATUS_ACTIVE",
"start":1372608000000,
"duration":1,
"end":1372694399999,
"startIsMilestone":false,
"endIsMilestone":false,
"collapsed":false,
"assigs":[]
}
],
"selectedRow":8,
"deletedTaskIds":[],
"resources":
[
{
"id":"tmp_1",
"name":"Resource 1"
}
],
"roles":[
{
"id":"tmp_1",
"name":"Project Manager"
}
],
"canWrite":true,
"canWriteOnParent":true
}
and this is how i mapped it
public class Attributes
{
public List<Task> _Task { get; set; }
public List<Resource> _Resource { get; set; }
public List<Role> _Role { get; set; }
public bool _canWrite { get; set; } //"canWrite":true,
public bool _canWriteOnParent { get; set; } //"canWriteOnParent":true,
public bool _selectedRow { get; set; } //"selectedRow":0,
public string [] _DeletedTaskIds { get; set; } //"deletedTaskIds":[],
}
public class Task
{
private string _id { get; set; }
private string _name { get; set; }
private string _code { get; set; }
private int _level { get; set; }
private string _status { get; set; }
private int _start { get; set; } //“start”:1348696800000,
private int _duration { get; set; } //“duration”:10,
private int _end { get; set; } //“end”:1349906399999,
private bool _startIsMilestone { get; set; } //“startIsMilestone”:false,
private bool _endIsMilestone { get; set; } //“endIsMilestone”:false,
public List<Assign> _assigns { get; set; } //“assigs”:[…],
private string _depends { get; set; } //“depends”:”7:3,8″,
private string _description { get; set; } //“description”:”Approval of testing”,
private int _progress { get; set; } //“progress”:20
}
public class Assign
{
private string _resourceId { get; set; } //“resourceId”:”tmp_1″,
private string _id { get; set; } //“id”:”tmp_1345560373990″,
private string _roleId { get; set; } //“roleId”:”tmp_1″,
private string _effort { get; set; } //“effort”:36000000
}
public class Resource
{
private string _id { get; set; } //“id”:”tmp_1″,
private string _name { get; set; } //“name”:”Resource 1″
}
public class Role
{
private string _id { get; set; } //“id”:”tmp_1″,
private string _name { get; set; } //“name”:”Project Manager”
}
if I'm doing it right, how can I serialize it into an object and send in order to send it to client side ?
Here is a link to a fantastic tool that maps Json to C#, here is what your mapping should look like:
public class Task
{
public object id { get; set; }
public string name { get; set; }
public string code { get; set; }
public int level { get; set; }
public string status { get; set; }
public object start { get; set; }
public int duration { get; set; }
public object end { get; set; }
public bool startIsMilestone { get; set; }
public bool endIsMilestone { get; set; }
public bool collapsed { get; set; }
public List<object> assigs { 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; }
}
public class RootObject
{
public List<Task> tasks { get; set; }
public int selectedRow { get; set; }
public List<object> deletedTaskIds { get; set; }
public List<Resource> resources { get; set; }
public List<Role> roles { get; set; }
public bool canWrite { get; set; }
public bool canWriteOnParent { get; set; }
}
There is also another slick way of mapping json to C# (I believe it comes with Visual Studio 2012 -> Web Essentials), you can go Edit-> Paste Special-> Paste JSON as Classes
EDIT
Since you've asked using Json.NET (you can get it from NuGet) you can deserialize your json like this:
RootObject deserialized = JsonConvert.DeserializeObject<RootObject>(data);
The format for classes and their properties you need to change. Here is the correct format.
Try it.
public class Task
{
public object id { get; set; }
public string name { get; set; }
public string code { get; set; }
public int level { get; set; }
public string status { get; set; }
public object start { get; set; }
public int duration { get; set; }
public object end { get; set; }
public bool startIsMilestone { get; set; }
public bool endIsMilestone { get; set; }
public bool collapsed { get; set; }
public List<object> assigs { 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; }
}
public class RootObject
{
public List<Task> tasks { get; set; }
public int selectedRow { get; set; }
public List<object> deletedTaskIds { get; set; }
public List<Resource> resources { get; set; }
public List<Role> roles { get; set; }
public bool canWrite { get; set; }
public bool canWriteOnParent { get; set; }
}

Categories

Resources