How to parse this http response in C# - c#

How would I parse this response using C#?
[
{
"date":"2016-10-01",
"stats":[
{
"type":"subuser",
"name":"coolguy#yahoo.com",
"metrics":{
"blocks":23,
"bounce_drops":164,
"bounces":19,
"clicks":0,
"deferred":412,
"delivered":3435,
"invalid_emails":27,
"opens":0,
"processed":3481,
"requests":3675,
"spam_report_drops":3,
"spam_reports":0,
"unique_clicks":0,
"unique_opens":0,
"unsubscribe_drops":0,
"unsubscribes":0
}
}
]
},
{
"date":"2016-10-02",
"stats":[
{
"type":"subuser",
"name":"coolguy#yahoo.com",
"metrics":{
"blocks":0,
"bounce_drops":0,
"bounces":0,
"clicks":0,
"deferred":95,
"delivered":0,
"invalid_emails":0,
"opens":0,
"processed":0,
"requests":0,
"spam_report_drops":0,
"spam_reports":0,
"unique_clicks":0,
"unique_opens":0,
"unsubscribe_drops":0,
"unsubscribes":0
}
}
]
}
]

Using JsonConvert deserialize it to dynamic as below or create a matching class structure and deserialize it to that.
using Newtonsoft.Json;
.....
string json = File.ReadAllText("data.txt");
var deserializedData = JsonConvert.DeserializeObject<dynamic>(json);
Using json2csharp your classes should look like:
public class Metrics
{
public int blocks { get; set; }
public int bounce_drops { get; set; }
public int bounces { get; set; }
public int clicks { get; set; }
public int deferred { get; set; }
public int delivered { get; set; }
public int invalid_emails { get; set; }
public int opens { get; set; }
public int processed { get; set; }
public int requests { get; set; }
public int spam_report_drops { get; set; }
public int spam_reports { get; set; }
public int unique_clicks { get; set; }
public int unique_opens { get; set; }
public int unsubscribe_drops { get; set; }
public int unsubscribes { get; set; }
}
public class Stat
{
public string type { get; set; }
public string name { get; set; }
public Metrics metrics { get; set; }
}
public class RootObject
{
public string date { get; set; }
public List<Stat> stats { get; set; }
}
These generated classes can be improved - for example not storing the date in a string but a DateTime
string json = File.ReadAllText("data.txt");
RootObject deserializedData = JsonConvert.DeserializeObject<RootObject>(json);

Related

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

Getting a JsonSerializationException when trying to deserialize PlayerStats

I want to insert into my class data from JSON but I got a Newtonsoft.Json.JsonSerializationException.
My PlayerStats class is good, I think, and I don't know why it's not working.
I can download and print JSON to the console but my code stops working at the point when I try to deserialize. I tried to add settings to deserialize but it's still not working.
Here is my code:
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Net;
namespace DiscordBot
{
class Osu
{
public string _nickname;
private string _key = "key";
public class PlayerStats
{
[JsonProperty("user_id")]
public int UserId { get; set; }
[JsonProperty("username")]
public string UserName { get; set; }
[JsonProperty("count300")]
public int Count300 { get; set; }
[JsonProperty("count100")]
public int Count100 { get; set; }
[JsonProperty("count50")]
public int Count50 { get; set; }
[JsonProperty("playcount")]
public int PlayCount { get; set; }
[JsonProperty("ranked_score")]
public long RankedScore { get; set; }
[JsonProperty("total_score")]
public long TotalScore { get; set; }
[JsonProperty("pp_rank")]
public int PpRank { get; set; }
[JsonProperty("level")]
public double Level { get; set; }
[JsonProperty("pp_raw")]
public double RawPp { get; set; }
[JsonProperty("accuracy")]
public double Accuracy { get; set; }
[JsonProperty("count_rank_ss")]
public int CountRankSs { get; set; }
[JsonProperty("count_rank_ssh")]
public int CoundRankSsh { get; set; }
[JsonProperty("count_rank_s")]
public int CountRankS { get; set; }
[JsonProperty("count_rank_sh")]
public int CountRankSh { get; set; }
[JsonProperty("count_rank_a")]
public int CountRankA { get; set; }
[JsonProperty("country")]
public string Country { get; set; }
[JsonProperty("pp_country_rank")]
public int PpCountryRank { get; set; }
}
public PlayerStats GetUserStats()
{
string json = string.Empty;
var result = JsonConvert.DeserializeObject<PlayerStats>(json);
try
{
string url = #"https://osu.ppy.sh/api/get_user";
using (WebClient wc = new WebClient())
{
wc.QueryString.Add("k", _key);
wc.QueryString.Add("u", _nickname);
wc.QueryString.Add("m", "0");
json = wc.DownloadString(url);
Console.WriteLine(json);
result = JsonConvert.DeserializeObject<PlayerStats>(json);
return result;
}
}
catch (WebException ex)
{
Console.WriteLine("Osu Error: " + ex.Status);
}
return result;
}
}
}
JSON:
[
{
"user_id":"10415972"
,"username":"iGruby"
,"count300":"851431"
,"count100":"15449 6"
,"count50":"19825"
,"playcount":"7129"
,"ranked_score":"453511877"
,"total_score" :"2735863526"
,"pp_rank":"147461"
,"level":"74.5611"
,"pp_raw":"1642.73"
,"accuracy" :"94.46521759033203"
,"count_rank_ss":"13"
,"count_rank_ssh":"2"
,"count_rank_s":"3 6"
,"count_rank_sh":"13"
,"count_rank_a":"65"
,"country":"PL"
,"pp_country_rank":"77 20"
,"events":[]
}
]
Refer this Tested Answer from the file I have loaded your json and DeserializeObject check my model also and how I am DeserializeObject
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
string data = File.ReadAllText("D://readjson.txt");
var obj = JsonConvert.DeserializeObject<List<RootObject>>(data);
}
}
public class RootObject
{
public string user_id { get; set; }
public string username { get; set; }
public string count300 { get; set; }
public string count100 { get; set; }
public string count50 { get; set; }
public string playcount { get; set; }
public string ranked_score { get; set; }
public string total_score { get; set; }
public string pp_rank { get; set; }
public string level { get; set; }
public string pp_raw { get; set; }
public string accuracy { get; set; }
public string count_rank_ss { get; set; }
public string count_rank_ssh { get; set; }
public string count_rank_s { get; set; }
public string count_rank_sh { get; set; }
public string count_rank_a { get; set; }
public string country { get; set; }
public string pp_country_rank { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public List<object> events { get; set; }
}
}
Pp_country_rank and count_rank_s contains a space. This is trying to be parsed to an integer.
"count_rank_s":"3 6"
,"count_rank_sh":"13"
,"count_rank_a":"65"
,"country":"PL"
,"pp_country_rank":"77 20"

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

How to parse specific data from JSON response [duplicate]

This question already has answers here:
How can I deserialize JSON with C#?
(19 answers)
Closed 5 years ago.
I am trying to parse JSON response using newtownsoft.json trying to parse the followers count and writeline.
This is the code:
using Newtonsoft.Json;
using System;
using System.IO;
using System.Net;
namespace J2C
{
class Checker
{
static void Main(string[] args)
{
var client = new WebClient();
var text = client.DownloadString("https://www.instagram.com/2saleapp/?__a=1");
User userObject = JsonConvert.DeserializeObject<User>(text);
Console.WriteLine("Followers count =" + userObject.followed_by);
Console.ReadKey();
}
}
}
and this is the API response:
{
"user": {
"biography": "Install 2Sale app to post your AD instantly!\nSnap, post, and sell. Its time to sale.",
"blocked_by_viewer": false,
"country_block": false,
"external_url": "http://autoigs.com/2sale_install",
"external_url_linkshimmed": "http://l.instagram.com/?u=http%3A%2F%2Fautoigs.com%2F2sale_install&e=ATMoKdz87_iz044M0ebrfU95WQT7JqBpnlGiGH9UDOsn7dRax7G6ZMxjh7wMuHY",
"followed_by": {
"count": 6511
},
"followed_by_viewer": false,
"follows": {
"count": 19
},
I just want to WriteLine Followed_by count numbers.
Any one can help me?
thank you
Copy the raw json to the clipboard. In Visual Studio menu select Edit > Paste Special > Paste JSON As Classes (this item is present at least since version VS2015. For earlier versions see). This will generate a set of classes.
public class Rootobject
{
public User user { get; set; }
public string logging_page_id { get; set; }
}
public class User
{
public string biography { get; set; }
public bool blocked_by_viewer { get; set; }
public bool country_block { get; set; }
public string external_url { get; set; }
public string external_url_linkshimmed { get; set; }
public Followed_By followed_by { get; set; }
public bool followed_by_viewer { get; set; }
public Follows follows { get; set; }
public bool follows_viewer { get; set; }
public string full_name { get; set; }
public bool has_blocked_viewer { get; set; }
public bool has_requested_viewer { get; set; }
public string id { get; set; }
public bool is_private { get; set; }
public bool is_verified { get; set; }
public string profile_pic_url { get; set; }
public string profile_pic_url_hd { get; set; }
public bool requested_by_viewer { get; set; }
public string username { get; set; }
public object connected_fb_page { get; set; }
public Media media { get; set; }
}
public class Followed_By
{
public int count { get; set; }
}
public class Follows
{
public int count { get; set; }
}
public class Media
{
public Node[] nodes { get; set; }
public int count { get; set; }
public Page_Info page_info { get; set; }
}
public class Page_Info
{
public bool has_next_page { get; set; }
public string end_cursor { get; set; }
}
public class Node
{
public string __typename { get; set; }
public string id { get; set; }
public bool comments_disabled { get; set; }
public Dimensions dimensions { get; set; }
public object gating_info { get; set; }
public string media_preview { get; set; }
public Owner owner { get; set; }
public string thumbnail_src { get; set; }
public object[] thumbnail_resources { get; set; }
public bool is_video { get; set; }
public string code { get; set; }
public int date { get; set; }
public string display_src { get; set; }
public string caption { get; set; }
public Comments comments { get; set; }
public Likes likes { get; set; }
public int video_views { get; set; }
}
public class Dimensions
{
public int height { get; set; }
public int width { get; set; }
}
public class Owner
{
public string id { get; set; }
}
public class Comments
{
public int count { get; set; }
}
public class Likes
{
public int count { get; set; }
}
Next, use the Rootobject. It's supposed to work.
var client = new WebClient();
var text = client.DownloadString("https://www.instagram.com/2saleapp/?__a=1");
Rootobject rootObject = JsonConvert.DeserializeObject<Rootobject>(text);
Console.WriteLine("Followers count =" + rootObject.user.followed_by.count);
In general, you should change the naming to conform to the generally accepted naming rules. You should use the JsonProperty attribute.
public class Rootobject
{
[JsonProperty("user")]
public User User { get; set; }
[JsonProperty("logging_page_id")]
public string LoggingPageId { get; set; }
}
And so on.
Create a class with name User in order to deserialize json string to User.
public class User
{
public string biography { get; set; }
public bool blocked_by_viewer { get; set; }
public bool country_block { get; set; }
public string external_url { get; set; }
public string external_url_linkshimmed { get; set; }
public FollowedBy followed_by { get; set; }
public string followed_by_viewer { get; set; }
public Follow follows { get; set; }
}
public class FollowedBy
{
public int count { get; set; }
}
public class Follow
{
public int count { get; set; }
}
After getting json string result using the below line for DeserializeObject to User and then assign it to new User object , after that use userObject for showing result.
User userObject = JsonConvert.DeserializeObject<User>(jsonString);
Now you have a user object that fill property with the API response.

Put JSON items into a WPF GRID in 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>

Categories

Resources