Trying best how to take the following classes and deserialize a Json file to return each class values back to Simpl+. I am able to receive the Total value but anything in a list I am at a lost.
public class Client
{
public string clientId { get; set; }
public string locale { get; set; }
public string location { get; set; }
public string auxiliaryId { get; set; }
public string description { get; set; }
public string type { get; set; }
public string typeDescription { get; set; }
public Hardware hardware { get; set; }
public Network network { get; set; }
}
public class Hardware
{
public string type { get; set; }
public string softwareVersion { get; set; }
public string serialNumber { get; set; }
public string hardwareVersion { get; set; }
public string model { get; set; }
}
public class Network
{
public string ip { get; set; }
public string mac { get; set; }
public object homepage { get; set; }
public string dhcpSubnet { get; set; }
}
public class Result
{
public List<Client> clients { get; set; }
public string total { get; set; }
public int limit { get; set; }
public int page { get; set; }
}
public class Root
{
public string jsonrpc { get; set; }
public object id { get; set; }
public Result result { get; set; }
}
I was able to resolve this by adding the following to the foreach statement:
args.MyIndex = (ushort)(rootObject.TriplePlayResult.clients.IndexOf(item) + 1);
I know [FromBody] allows only one complex type as a parameter. I just wanted to know, is there any other way to do so? Any help or knowledge would be greatly appreciated! Thanks! :)
This is my controller
public HttpResponseMessage Post([FromBody] List<TranInOutDtl> tranInOutDtl, List<TranInOutDtlsub> tranDtlSub, List<TranInOutDtlsub> tranDtlSub)
This is my complex object below
public partial class TranInOutDtl
{
public int Tranno { get; set; }
public int Trannosub { get; set; }
public string ProdTypeDesc { get; set; }
public string BatchNo { get; set; }
public string Itemno { get; set; }
public string ItemDesc { get; set; }
public decimal ScanPendQty { get; set; }
public int TotalBoxqty { get; set; }
public decimal Quantity { get; set; }
public int BoxQty { get; set; }
public bool Isdone { get; set; }
public int PKId { get; set; }
public int PKSubId { get; set; }
public string PkBxDesc { get; set; }
public int BoxSz { get; set; }
}
public partial class TranInOutDtlsub
{
public int Tranno { get; set; }
public int Trannosub { get; set; }
public int Trannosub1 { get; set; }
public string RackShlvNo { get; set; }
public string ShlvNo { get; set; }
public int ShlvBoxQty { get; set; }
public decimal Quantity { get; set; }
public int BoxQty { get; set; }
public bool Isdonesub { get; set; }
public string RkShlvSelType { get; set; }
public string RkShCatUId { get; set; }
public string RackCatDesc { get; set; }
public string RkShCatColorCode { get; set; }
}
public partial class TranInOutRackScan
{
public int Tranno { get; set; }
public int Trannosub { get; set; }
public int Trannosub1 { get; set; }
public int Srno { get; set; }
public string BarcodeNo { get; set; }
public decimal Quantity { get; set; }
public int BoxQty { get; set; }
public string InOut { get; set; }
public int PackMaster_ID { get; set; }
public int Pack_type_ID { get; set; }
}
As it was mentioned by DavidG you could create any complex types that will suit your specific needs so for example
public class TranInOutContainer
{
public List<TranInOutDtl> TranInOutDtl Dtl {get; set;}
public List<TranInOutDtlsub> TranDtlSub DtlSub {get; set;}
....
}
will be valid solution for your problem
You could also use dynamic type ofc but it should be used only if no other solution exists
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; }
}
I am using multiple levels of JSON data coming into php from a C# application, as in:
public class User_Group
{
public int ID_UserGroup { get; set; }
public string Name_UserGroup { get; set; }
public int UserID { get; set; }
}
public class User_Role
{
public int ID_User { get; set; }
public string Role_User { get; set; }
public string User_Role_Description { get; set; }
public List<User_Group> UserGroup { get; set; }
}
public class Stand_Orte
{
public int ID { get; set; }
public string Bezeichnung { get; set; }
public List<Modul> modul { get; set; }
}
public class Modul
{
public string ID { get; set; }
public string Seriennummer { get; set; }
public string Bezeichnung { get; set; }
public string StandortID { get; set; }
public List<Mess_Kanal> MessKanal { get; set; }
}
public class Mess_Kanal
{
public string ID { get; set; }
public string ModulID { get; set; }
public List<LogMess_Daten> LogMessDaten { get; set; }
}
public class LogMess_Daten
{
public string KanalID { get; set; }
public string Zeitstempel { get; set; }
}
public class RootObject
{
public int ID_Project { get; set; }
public string Name_Project { get; set; }
public int Receiver_ID { get; set; }
public string Receiver_Name { get; set; }
public int UserID { get; set; }
public User_Role UserRole { get; set; }
public Stand_Orte Standorte { get; set; }
}
I have an issue with accessing the 3rd level data elements.
For Eg., I am able to get the values uptil Project-> Stand_Orte-> Modul. but after that Project-> Stand_Orte-> Modul-> MessKanal Throws an error in PHP as " Trying to get property of non-object ".
I tried the following:
$phpArray['project']->Standorte[0]->modul[0]->MessKanal[0]->ID
$messkanals=$phpArray->Standorte->modul->MessKanal;
And then used a "foreach ($messkanals as $messkanal)" to insert MessKanal data into MYSQL.
it gives me the following errors respectively.
Cannot use object of type stdClass as array
Trying to get property of non-object
does anyone have any idea?
Thanks,
Revathy
I am using .net to call to a webservice then parse it to usable data.
Right now I am experimenting with this call: http://www.reddit.com/r/all.json
Which returns: http://pastebin.com/AbV4yVuC
This is put in to a string, which I called jsontxt.
I am using JSON.NET to parse the information but it doesn't seem to be working. I initially tried to deserialize it as an object and it didn't work as nothing is put in to the variable
Then I tried to deserialize it as a dataset and I'm having no luck again. My error was
An unhandled exception of type 'Newtonsoft.Json.JsonException' occurred in Newtonsoft.Json.dll
MY CODE:
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace tutorialresult1
{
class Program
{
static void Main(string[] args)
{
using (var webClient = new System.Net.WebClient())
{
var jsontxt = webClient.DownloadString("http://www.reddit.com/r/all.json");
// Console.Write(json);
// -----Deserializing by Object--------------
//MediaEmbed account = JsonConvert.DeserializeObject<MediaEmbed>(jsontxt);
//Console.WriteLine(account.width); //COMES OUT TO NULL
// -----Deserializing by DataSet--------------
DataSet dataSet = JsonConvert.DeserializeObject<DataSet>(jsontxt);
DataTable dataTable = dataSet.Tables["Children"];
Console.WriteLine(dataTable.Rows.Count);
}
}
public class MediaEmbed
{
public string content { get; set; }
public int width { get; set; }
public bool scrolling { get; set; }
public int height { get; set; }
}
.... //rest of classes here for each json which were generated with http://json2csharp.com/
}
}
I'm just trying to make the JSON easily accessible by parsing it.
Using json2charp I generated the following set of classes. Using those you should be able to deserialize the JSON into RootObject using JSON.NET.
var account = JsonConvert.DeserializeObject<RootObject>(jsontxt);
.
public class MediaEmbed
{
public string content { get; set; }
public int? width { get; set; }
public bool? scrolling { get; set; }
public int? height { get; set; }
}
public class Oembed
{
public string provider_url { get; set; }
public string description { get; set; }
public string title { get; set; }
public string url { get; set; }
public string type { get; set; }
public string author_name { get; set; }
public int height { get; set; }
public int width { get; set; }
public string html { get; set; }
public int thumbnail_width { get; set; }
public string version { get; set; }
public string provider_name { get; set; }
public string thumbnail_url { get; set; }
public int thumbnail_height { get; set; }
public string author_url { get; set; }
}
public class SecureMedia
{
public Oembed oembed { get; set; }
public string type { get; set; }
}
public class SecureMediaEmbed
{
public string content { get; set; }
public int? width { get; set; }
public bool? scrolling { get; set; }
public int? height { get; set; }
}
public class Oembed2
{
public string provider_url { get; set; }
public string description { get; set; }
public string title { get; set; }
public int thumbnail_width { get; set; }
public int height { get; set; }
public int width { get; set; }
public string html { get; set; }
public string version { get; set; }
public string provider_name { get; set; }
public string thumbnail_url { get; set; }
public string type { get; set; }
public int thumbnail_height { get; set; }
public string url { get; set; }
public string author_name { get; set; }
public string author_url { get; set; }
}
public class Media
{
public string type { get; set; }
public Oembed2 oembed { get; set; }
}
public class Data2
{
public string domain { get; set; }
public object banned_by { get; set; }
public MediaEmbed media_embed { get; set; }
public string subreddit { get; set; }
public string selftext_html { get; set; }
public string selftext { get; set; }
public object likes { get; set; }
public SecureMedia secure_media { get; set; }
public string link_flair_text { get; set; }
public string id { get; set; }
public int gilded { get; set; }
public SecureMediaEmbed secure_media_embed { get; set; }
public bool clicked { get; set; }
public bool stickied { get; set; }
public string author { get; set; }
public Media media { get; set; }
public int score { get; set; }
public object approved_by { get; set; }
public bool over_18 { get; set; }
public bool hidden { get; set; }
public string thumbnail { get; set; }
public string subreddit_id { get; set; }
public object edited { get; set; }
public string link_flair_css_class { get; set; }
public object author_flair_css_class { get; set; }
public int downs { get; set; }
public bool saved { get; set; }
public bool is_self { get; set; }
public string permalink { get; set; }
public string name { get; set; }
public double created { get; set; }
public string url { get; set; }
public object author_flair_text { get; set; }
public string title { get; set; }
public double created_utc { get; set; }
public int ups { get; set; }
public int num_comments { get; set; }
public bool visited { get; set; }
public object num_reports { get; set; }
public object distinguished { get; set; }
}
public class Child
{
public string kind { get; set; }
public Data2 data { get; set; }
}
public class Data
{
public string modhash { get; set; }
public List<Child> children { get; set; }
public string after { get; set; }
public object before { get; set; }
}
public class RootObject
{
public string kind { get; set; }
public Data data { get; set; }
}
You are trying to deserialize a json-string into a dataset-object. But the json-string doesn't have the format of a dataset. So you need to create a class which matches the json or deserialize it into a dictionary or sth. like this.
Have you tried deserialize using the following? Seems to be more robust for me.
using System.Web.Script.Serialization;
...
var x = new JavaScriptSerializer().Deserialize<Obj_type>(jsonstring);
http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer%28v=vs.110%29.aspx
as purplej0kr mentioned you will need to have a .Net model to use for Obj_type (and it will need to match the object you are parsing) or this will not work.
You will need the System.Web.Extensions.dll referenced in your project (right click add reference, dll is usually under 'Assemblies'). Otherwise:
Where can I find the assembly System.Web.Extensions dll?