Deserializing Json Data to C# Using Json.Net

json.net deserialize a json object in c#

Thats because the json does not match

Extract 730 object then parse it into your defined classes

public static void Main()
{
string json = new WebClient().DownloadString("http://store.steampowered.com/api/appdetails?appids=730");
JObject jObject = JObject.Parse(json);
var root = jObject["730"].Value<JObject>().ToObject<steamstore>();
Console.WriteLine(root.data.name);
Console.ReadKey();
}

Here is the Json from http://store.steampowered.com/api/appdetails?appids=730

{"730":{"success":true,"data":{"type":"game","name":"Counter-Strike: Global Offensive","steam_appid":730,"required_age":0,"is_free":false,"controller_support":"full","detailed_description":"Counter-Strike: Global Offensive (CS: GO) will expand upon the team-based action gameplay that it pioneered when it was launched 14 years ago.<br \/>\r\n<br \/>\r\nCS: GO features new maps, characters, and weapons and delivers updated versions of the classic CS content (de_dust, etc.). In addition, CS: GO will introduce new gameplay modes, matchmaking, leader boards, and more.<br \/>\r\n<br \/>\r\n"Counter-Strike took the gaming industry by surprise when the unlikely MOD became the most played online PC action game in the world almost immediately after its release in August 1999," said Doug Lombardi at Valve. "For the past 12 years, it has continued to be one of the most-played games in the world, headline competitive gaming tournaments and selling over 25 million units worldwide across the franchise. CS: GO promises to expand on CS' award-winning gameplay and deliver it to gamers on the PC as well as the next gen consoles and the Mac."","about_the_game":"Counter-Strike: Global Offensive (CS: GO) will expand upon the team-based action gameplay that it pioneered when it was launched 14 years ago.<br \/>\r\n<br \/>\r\nCS: GO features new maps, characters, and weapons and delivers updated versions of the classic CS content (de_dust, etc.). In addition, CS: GO will introduce new gameplay modes, matchmaking, leader boards, and more.<br \/>\r\n<br \/>\r\n"Counter-Strike took the gaming industry by surprise when the unlikely MOD became the most played online PC action game in the world almost immediately after its release in August 1999," said Doug Lombardi at Valve. "For the past 12 years, it has continued to be one of the most-played games in the world, headline competitive gaming tournaments and selling over 25 million units worldwide across the franchise. CS: GO promises to expand on CS' award-winning gameplay and deliver it to gamers on the PC as well as the next gen consoles and the Mac."","supported_languages":"Czech, Danish, Dutch, English<strong>*<\/strong>, Finnish, French, German, Hungarian, Italian, Japanese, Korean, Norwegian, Polish, Portuguese, Portuguese-Brazil, Romanian, Russian, Simplified Chinese, Spanish, Swedish, Thai, Traditional Chinese, Turkish, Bulgarian, Ukrainian<br><strong>*<\/strong>languages with full audio support","header_image":"http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/730\/header.jpg?t=1467065027","website":"http:\/\/blog.counter-strike.net\/","pc_requirements":{"minimum":"<strong>Minimum:<\/strong>\r<br><ul class=\"bb_ul\"><li><strong>OS:<\/strong> Windows\u00ae 7\/Vista\/XP\r<br><\/li><li><strong>Processor:<\/strong> Intel\u00ae Core\u2122 2 Duo E6600 or AMD Phenom\u2122 X3 8750 processor or better\r<br><\/li><li><strong>Memory:<\/strong> 2 GB RAM\r<br><\/li><li><strong>Graphics:<\/strong> Video card must be 256 MB or more and should be a DirectX 9-compatible with support for Pixel Shader 3.0\r<br><\/li><li><strong>DirectX:<\/strong> Version 9.0c\r<br><\/li><li><strong>Storage:<\/strong> 8 GB available space\r<\/li><\/ul>"},"mac_requirements":{"minimum":"<strong>Minimum:<\/strong>\r<br><ul class=\"bb_ul\"><li><strong>OS:<\/strong> MacOS X 10.6.6 or higher\r<br><\/li><li><strong>Processor:<\/strong> Intel Core Duo Processor (2GHz or better)\r<br><\/li><li><strong>Memory:<\/strong> 2 GB RAM\r<br><\/li><li><strong>Graphics:<\/strong> ATI Radeon HD 2400 or better \/ NVidia 8600M or better\r<br><\/li><li><strong>Storage:<\/strong> 8 GB available space\r<\/li><\/ul>"},"linux_requirements":{"minimum":"<strong>Minimum:<\/strong>\r<br><ul class=\"bb_ul\"><li><strong>OS:<\/strong> Ubuntu 12.04\r<br><\/li><li><strong>Processor:<\/strong> 64-bit Dual core from Intel or AMD at 2.8 GHz\r<br><\/li><li><strong>Memory:<\/strong> 4 GB RAM\r<br><\/li><li><strong>Graphics:<\/strong> nVidia GeForce 8600\/9600GT, ATI\/AMD Radeon HD2600\/3600 (Graphic Drivers: nVidia 310, AMD 12.11), OpenGL 2.1\r<br><\/li><li><strong>Storage:<\/strong> 8 GB available space\r<br><\/li><li><strong>Sound Card:<\/strong> OpenAL Compatible Sound Card\r<\/li><\/ul>"},"developers":["Valve"],"publishers":["Valve"],"price_overview":{"currency":"SGD","initial":1500,"final":1500,"discount_percent":0},"packages":[54029],"package_groups":[{"name":"default","title":"Buy Counter-Strike: Global Offensive","description":"","selection_text":"Select a purchase option","save_text":"","display_type":0,"is_recurring_subscription":"false","subs":[{"packageid":54029,"percent_savings_text":"","percent_savings":0,"option_text":"Counter-Strike: Global Offensive - S$15.00","option_description":"","can_get_free_license":"0","is_free_license":false,"price_in_cents_with_discount":1500}]}],"platforms":{"windows":true,"mac":true,"linux":true},"metacritic":{"score":83,"url":"http:\/\/www.metacritic.com\/game\/pc\/counter-strike-global-offensive?ftag=MCD-06-10aaa1f"},"categories":[{"id":1,"description":"Multi-player"},{"id":22,"description":"Steam Achievements"},{"id":28,"description":"Full controller support"},{"id":29,"description":"Steam Trading Cards"},{"id":30,"description":"Steam Workshop"},{"id":35,"description":"In-App Purchases"},{"id":8,"description":"Valve Anti-Cheat enabled"},{"id":15,"description":"Stats"}],"genres":[{"id":"1","description":"Action"}],"screenshots":[{"id":0,"path_thumbnail":"http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/730\/ss_34090867f1a02b6c17652ba9043e3f622ed985a9.600x338.jpg?t=1467065027","path_full":"http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/730\/ss_34090867f1a02b6c17652ba9043e3f622ed985a9.1920x1080.jpg?t=1467065027"},{"id":1,"path_thumbnail":"http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/730\/ss_1d30c9a215fd621e2fd74f40d93b71587bf6409c.600x338.jpg?t=1467065027","path_full":"http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/730\/ss_1d30c9a215fd621e2fd74f40d93b71587bf6409c.1920x1080.jpg?t=1467065027"},{"id":2,"path_thumbnail":"http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/730\/ss_baa02e979cd3852e3c4182afcd603ab64e3502f9.600x338.jpg?t=1467065027","path_full":"http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/730\/ss_baa02e979cd3852e3c4182afcd603ab64e3502f9.1920x1080.jpg?t=1467065027"},{"id":3,"path_thumbnail":"http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/730\/ss_ffe584c163a2b16e9c1b733b1c8e2ba669fb1204.600x338.jpg?t=1467065027","path_full":"http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/730\/ss_ffe584c163a2b16e9c1b733b1c8e2ba669fb1204.1920x1080.jpg?t=1467065027"},{"id":4,"path_thumbnail":"http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/730\/ss_d87c102d028d545c877363166c9d8377014f0c23.600x338.jpg?t=1467065027","path_full":"http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/730\/ss_d87c102d028d545c877363166c9d8377014f0c23.1920x1080.jpg?t=1467065027"},{"id":5,"path_thumbnail":"http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/730\/ss_9d0735a5fbe523fd39f2c69c047019843c326cea.600x338.jpg?t=1467065027","path_full":"http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/730\/ss_9d0735a5fbe523fd39f2c69c047019843c326cea.1920x1080.jpg?t=1467065027"},{"id":6,"path_thumbnail":"http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/730\/ss_9d889bec419cf38910ccf72dd80f9260227408ee.600x338.jpg?t=1467065027","path_full":"http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/730\/ss_9d889bec419cf38910ccf72dd80f9260227408ee.1920x1080.jpg?t=1467065027"},{"id":7,"path_thumbnail":"http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/730\/ss_ccc4ce6edd4c454b6ce7b0757e633b63aa93921d.600x338.jpg?t=1467065027","path_full":"http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/730\/ss_ccc4ce6edd4c454b6ce7b0757e633b63aa93921d.1920x1080.jpg?t=1467065027"},{"id":8,"path_thumbnail":"http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/730\/ss_9db552fd461722f1569e3292d8f2ea654c8ffdef.600x338.jpg?t=1467065027","path_full":"http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/730\/ss_9db552fd461722f1569e3292d8f2ea654c8ffdef.1920x1080.jpg?t=1467065027"},{"id":9,"path_thumbnail":"http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/730\/ss_74c1a0264ceaf57e5fb51d978205045223b48a18.600x338.jpg?t=1467065027","path_full":"http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/730\/ss_74c1a0264ceaf57e5fb51d978205045223b48a18.1920x1080.jpg?t=1467065027"},{"id":10,"path_thumbnail":"http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/730\/ss_7eaa83e44f5218a7bf5f88a0c750e36052e31d7d.600x338.jpg?t=1467065027","path_full":"http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/730\/ss_7eaa83e44f5218a7bf5f88a0c750e36052e31d7d.1920x1080.jpg?t=1467065027"},{"id":11,"path_thumbnail":"http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/730\/ss_68007896ad6071b7062bac530c481e097105efc0.600x338.jpg?t=1467065027","path_full":"http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/730\/ss_68007896ad6071b7062bac530c481e097105efc0.1920x1080.jpg?t=1467065027"},{"id":12,"path_thumbnail":"http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/730\/ss_2fcee01bace72bc47a2ad0ba82620588239e93df.600x338.jpg?t=1467065027","path_full":"http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/730\/ss_2fcee01bace72bc47a2ad0ba82620588239e93df.1920x1080.jpg?t=1467065027"},{"id":13,"path_thumbnail":"http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/730\/ss_f5875f8de419a3d5133ae7245b8296db2c027dd8.600x338.jpg?t=1467065027","path_full":"http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/730\/ss_f5875f8de419a3d5133ae7245b8296db2c027dd8.1920x1080.jpg?t=1467065027"},{"id":14,"path_thumbnail":"http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/730\/ss_36f82c71ee2180159b060b155bf3d06dd8167327.600x338.jpg?t=1467065027","path_full":"http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/730\/ss_36f82c71ee2180159b060b155bf3d06dd8167327.1920x1080.jpg?t=1467065027"}],"movies":[{"id":81958,"name":"CS:GO Trailer Long","thumbnail":"http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/81958\/movie.293x165.jpg?t=1459467902","webm":{"480":"http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/81958\/movie480.webm?t=1459467902","max":"http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/81958\/movie_max.webm?t=1459467902"},"highlight":true},{"id":2028288,"name":"CS: GO Pro Tip Series: TM","thumbnail":"http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/2028288\/movie.293x165.jpg?t=1459467945","webm":{"480":"http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/2028288\/movie480.webm?t=1459467945","max":"http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/2028288\/movie_max.webm?t=1459467945"},"highlight":false},{"id":2028287,"name":"CS: GO Pro Tip Series: sapphiRe","thumbnail":"http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/2028287\/movie.293x165.jpg?t=1459467936","webm":{"480":"http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/2028287\/movie480.webm?t=1459467936","max":"http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/2028287\/movie_max.webm?t=1459467936"},"highlight":false},{"id":2028286,"name":"CS: GO Pro Tip Series: AZK","thumbnail":"http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/2028286\/movie.293x165.jpg?t=1459467927","webm":{"480":"http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/2028286\/movie480.webm?t=1459467927","max":"http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/2028286\/movie_max.webm?t=1459467927"},"highlight":false},{"id":2028285,"name":"CS: GO Pro Tip Series: Fifflaren","thumbnail":"http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/2028285\/movie.293x165.jpg?t=1459467962","webm":{"480":"http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/2028285\/movie480.webm?t=1459467962","max":"http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/2028285\/movie_max.webm?t=1459467962"},"highlight":false},{"id":2028284,"name":"CS: GO Pro Tip Series: ruggah","thumbnail":"http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/2028284\/movie.293x165.jpg?t=1459467919","webm":{"480":"http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/2028284\/movie480.webm?t=1459467919","max":"http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/2028284\/movie_max.webm?t=1459467919"},"highlight":false},{"id":2028283,"name":"CS: GO Pro Tip Series: nEiLZiNHo","thumbnail":"http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/2028283\/movie.293x165.jpg?t=1459467911","webm":{"480":"http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/2028283\/movie480.webm?t=1459467911","max":"http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/2028283\/movie_max.webm?t=1459467911"},"highlight":false},{"id":2028289,"name":"CS: GO Pro Tip Series: Semphis","thumbnail":"http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/2028289\/movie.jpg?t=1459467954","webm":{"480":"http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/2028289\/movie480.webm?t=1459467954","max":"http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/2028289\/movie_max.webm?t=1459467954"},"highlight":false}],"recommendations":{"total":1385472},"achievements":{"total":167,"highlighted":[{"name":"Someone Set Up Us The Bomb","path":"http:\/\/cdn.akamai.steamstatic.com\/steamcommunity\/public\/images\/apps\/730\/9f60ea3c56b4ab248ab598bbd62568b953116301.jpg"},{"name":"Boomala Boomala","path":"http:\/\/cdn.akamai.steamstatic.com\/steamcommunity\/public\/images\/apps\/730\/325ccbd68e599083c1597fd90dc6d4265d1ca3b4.jpg"},{"name":"The Hurt Blocker","path":"http:\/\/cdn.akamai.steamstatic.com\/steamcommunity\/public\/images\/apps\/730\/9b8627953feca51a56f0c2ac871493c8634a1c07.jpg"},{"name":"Body Bagger","path":"http:\/\/cdn.akamai.steamstatic.com\/steamcommunity\/public\/images\/apps\/730\/b11ef0453168cd3d10684e184004f71dcc0faa82.jpg"},{"name":"Corpseman","path":"http:\/\/cdn.akamai.steamstatic.com\/steamcommunity\/public\/images\/apps\/730\/60d83a42df84fa5d84910af681370579e3bb16bf.jpg"},{"name":"God of War","path":"http:\/\/cdn.akamai.steamstatic.com\/steamcommunity\/public\/images\/apps\/730\/2c2bb56a4f7376b53eeaf8e6d84044460b0d1cf2.jpg"},{"name":"Second to None","path":"http:\/\/cdn.akamai.steamstatic.com\/steamcommunity\/public\/images\/apps\/730\/986a53e24114699cb1f230f52b55b27e0de28ecf.jpg"},{"name":"Counter-Counter-Terrorist","path":"http:\/\/cdn.akamai.steamstatic.com\/steamcommunity\/public\/images\/apps\/730\/c09cb3fe34841fd1000a48c3b7825c4fde026188.jpg"},{"name":"Rite of First Defusal","path":"http:\/\/cdn.akamai.steamstatic.com\/steamcommunity\/public\/images\/apps\/730\/b2027dac5a9883f0f145e78a33e531a58944f3ec.jpg"},{"name":"Short Fuse","path":"http:\/\/cdn.akamai.steamstatic.com\/steamcommunity\/public\/images\/apps\/730\/648550738f4845f12aa686a1b4ee8c4a51ec2348.jpg"}]},"release_date":{"coming_soon":false,"date":"22 Aug, 2012"},"support_info":{"url":"","email":""},"background":"http:\/\/cdn.akamai.steamstatic.com\/steam\/apps\/730\/page_bg_generated_v6b.jpg?t=1467065027"}}}

Deserialize JSON to C# Classes

Your problem is twofold:

  1. You don't have a class defined at the root level. The class structure needs to match the entire JSON, you can't just deserialize from the middle.
  2. Whenever you have an object whose keys can change, you need to use a Dictionary<string, T>. A regular class won't work for that; neither will a List<T>.

Make your classes like this:

class RootObject
{
[JsonProperty("results")]
public Results Results { get; set; }
}

class Results
{
[JsonProperty("jobcodes")]
public Dictionary<string, JobCode> JobCodes { get; set; }
}

class JobCode
{
[JsonProperty("_status_code")]
public string StatusCode { get; set; }
[JsonProperty("_status_message")]
public string StatusMessage { get; set; }
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
}

Then, deserialize like this:

RootObject obj = JsonConvert.DeserializeObject<RootObject>(json);

Working demo here

How to deserialize a JSON array into an object using Json.Net?

Json.Net does not have a facility to automatically map an array into a class. To do so you need a custom JsonConverter. Here is a generic converter that should work for you. It uses a custom [JsonArrayIndex] attribute to identify which properties in the class correspond to which indexes in the array. This will allow you to easily update your model if the JSON changes. Also, you can safely omit properties from your class that you don't need, such as Filler.

Here is the code:

public class JsonArrayIndexAttribute : Attribute
{
public int Index { get; private set; }
public JsonArrayIndexAttribute(int index)
{
Index = index;
}
}

public class ArrayToObjectConverter<T> : JsonConverter where T : class, new()
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(T);
}

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JArray array = JArray.Load(reader);

var propsByIndex = typeof(T).GetProperties()
.Where(p => p.CanRead && p.CanWrite && p.GetCustomAttribute<JsonArrayIndexAttribute>() != null)
.ToDictionary(p => p.GetCustomAttribute<JsonArrayIndexAttribute>().Index);

JObject obj = new JObject(array
.Select((jt, i) =>
{
PropertyInfo prop;
return propsByIndex.TryGetValue(i, out prop) ? new JProperty(prop.Name, jt) : null;
})
.Where(jp => jp != null)
);

T target = new T();
serializer.Populate(obj.CreateReader(), target);

return target;
}

public override bool CanWrite
{
get { return false; }
}

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}

To use the converter, you need to mark up your ChildModel class as shown below:

[JsonConverter(typeof(ArrayToObjectConverter<ChildModel>))]
class ChildModel
{
[JsonArrayIndex(0)]
public int ID { get; set; }
[JsonArrayIndex(1)]
public string StatusId { get; set; }
[JsonArrayIndex(2)]
public DateTime ContactDate { get; set; }
[JsonArrayIndex(3)]
public string State { get; set; }
[JsonArrayIndex(4)]
public string Status { get; set; }
[JsonArrayIndex(5)]
public string CustomerName { get; set; }
[JsonArrayIndex(6)]
public DateTime WorkStartDate { get; set; }
[JsonArrayIndex(7)]
public DateTime WorkEndDate { get; set; }
[JsonArrayIndex(8)]
public string Territory { get; set; }
[JsonArrayIndex(9)]
public string CustType { get; set; }
[JsonArrayIndex(10)]
public int JobOrder { get; set; }
[JsonArrayIndex(12)]
public string Link { get; set; }
}

Then just deserialize as usual and it should work as you wanted. Here is a demo: https://dotnetfiddle.net/n3oE3L

Note: I did not implement WriteJson, so if you serialize your model back to JSON, it will not serialize back to the array format; instead it will use the default object serialization.

Deserialize JSON into Object C#

You can use Visual Studio 2013, 2015 to create your model classes from a json, I did it and I parsed the JSON fine.
To use this feature, you must have JSON/XML in your clipboard, put your cursor inside a .cs file and then use the option Edit > Paste Special > Paste JSON AS Classes

Paste Special JSON as classes

Look the code that was generated:

public class Rootobject
{
public Class1[] Property1 { get; set; }
}

public class Class1
{
public int Rk { get; set; }
public int Gcar { get; set; }
public int Gtm { get; set; }
public string Date { get; set; }
public string Tm { get; set; }
public string Where { get; set; }
public string Opp { get; set; }
public string Rslt { get; set; }
public string Inngs { get; set; }
public int PA { get; set; }
public int AB { get; set; }
public int R { get; set; }
public int H { get; set; }
public int Doubles { get; set; }
public int Triples { get; set; }
public int HR { get; set; }
public int RBI { get; set; }
public int BB { get; set; }
public int IBB { get; set; }
public int SO { get; set; }
public int HBP { get; set; }
public int SH { get; set; }
public int SF { get; set; }
public int ROE { get; set; }
public int GDP { get; set; }
public int SB { get; set; }
public int CS { get; set; }
public float BA { get; set; }
public float OBP { get; set; }
public float SLG { get; set; }
public float OPS { get; set; }
public int BOP { get; set; }
public float aLI { get; set; }
public float WPA { get; set; }
public float RE24 { get; set; }
public int DFSDK { get; set; }
public float DFSFD { get; set; }
public string Pos { get; set; }
}

In runtime to deserialize JSON into this object created from Visual Studio, you can use Newtonsoft.Json, you can install this using nuget with the following command:

Install-Package Newtonsoft.Json

Now you can deserialized it, using the gerenric method DeserializedObject from the static class JsconCovert, like that:

Rootobject object = JsonConvert.DeserializeObject<Rootobject>(jsonString); 

Deserialize JSON into C# dynamic object?

If you are happy to have a dependency upon the System.Web.Helpers assembly, then you can use the Json class:

dynamic data = Json.Decode(json);

It is included with the MVC framework as an additional download to the .NET 4 framework. Be sure to give Vlad an upvote if that's helpful! However if you cannot assume the client environment includes this DLL, then read on.


An alternative deserialisation approach is suggested here. I modified the code slightly to fix a bug and suit my coding style. All you need is this code and a reference to System.Web.Extensions from your project:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Web.Script.Serialization;

public sealed class DynamicJsonConverter : JavaScriptConverter
{
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
{
if (dictionary == null)
throw new ArgumentNullException("dictionary");

return type == typeof(object) ? new DynamicJsonObject(dictionary) : null;
}

public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
{
throw new NotImplementedException();
}

public override IEnumerable<Type> SupportedTypes
{
get { return new ReadOnlyCollection<Type>(new List<Type>(new[] { typeof(object) })); }
}

#region Nested type: DynamicJsonObject

private sealed class DynamicJsonObject : DynamicObject
{
private readonly IDictionary<string, object> _dictionary;

public DynamicJsonObject(IDictionary<string, object> dictionary)
{
if (dictionary == null)
throw new ArgumentNullException("dictionary");
_dictionary = dictionary;
}

public override string ToString()
{
var sb = new StringBuilder("{");
ToString(sb);
return sb.ToString();
}

private void ToString(StringBuilder sb)
{
var firstInDictionary = true;
foreach (var pair in _dictionary)
{
if (!firstInDictionary)
sb.Append(",");
firstInDictionary = false;
var value = pair.Value;
var name = pair.Key;
if (value is string)
{
sb.AppendFormat("{0}:\"{1}\"", name, value);
}
else if (value is IDictionary<string, object>)
{
new DynamicJsonObject((IDictionary<string, object>)value).ToString(sb);
}
else if (value is ArrayList)
{
sb.Append(name + ":[");
var firstInArray = true;
foreach (var arrayValue in (ArrayList)value)
{
if (!firstInArray)
sb.Append(",");
firstInArray = false;
if (arrayValue is IDictionary<string, object>)
new DynamicJsonObject((IDictionary<string, object>)arrayValue).ToString(sb);
else if (arrayValue is string)
sb.AppendFormat("\"{0}\"", arrayValue);
else
sb.AppendFormat("{0}", arrayValue);

}
sb.Append("]");
}
else
{
sb.AppendFormat("{0}:{1}", name, value);
}
}
sb.Append("}");
}

public override bool TryGetMember(GetMemberBinder binder, out object result)
{
if (!_dictionary.TryGetValue(binder.Name, out result))
{
// return null to avoid exception. caller can check for null this way...
result = null;
return true;
}

result = WrapResultObject(result);
return true;
}

public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result)
{
if (indexes.Length == 1 && indexes[0] != null)
{
if (!_dictionary.TryGetValue(indexes[0].ToString(), out result))
{
// return null to avoid exception. caller can check for null this way...
result = null;
return true;
}

result = WrapResultObject(result);
return true;
}

return base.TryGetIndex(binder, indexes, out result);
}

private static object WrapResultObject(object result)
{
var dictionary = result as IDictionary<string, object>;
if (dictionary != null)
return new DynamicJsonObject(dictionary);

var arrayList = result as ArrayList;
if (arrayList != null && arrayList.Count > 0)
{
return arrayList[0] is IDictionary<string, object>
? new List<object>(arrayList.Cast<IDictionary<string, object>>().Select(x => new DynamicJsonObject(x)))
: new List<object>(arrayList.Cast<object>());
}

return result;
}
}

#endregion
}

You can use it like this:

string json = ...;

var serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new[] { new DynamicJsonConverter() });

dynamic obj = serializer.Deserialize(json, typeof(object));

So, given a JSON string:

{
"Items":[
{ "Name":"Apple", "Price":12.3 },
{ "Name":"Grape", "Price":3.21 }
],
"Date":"21/11/2010"
}

The following code will work at runtime:

dynamic data = serializer.Deserialize(json, typeof(object));

data.Date; // "21/11/2010"
data.Items.Count; // 2
data.Items[0].Name; // "Apple"
data.Items[0].Price; // 12.3 (as a decimal)
data.Items[1].Name; // "Grape"
data.Items[1].Price; // 3.21 (as a decimal)

Deserialize JSON as object or array with JSON.Net

You can change the property type for "data" in your model to dynamic or an object and check if it is an array on run-time.

Here's an example:

public class Response
{
[JsonProperty("status")]
public string Status { get; set; }
[JsonProperty("data")]
public dynamic Data { get; set; }
}


var response = JsonConvert.DeserializeJson<Response>(json);
.
.
.

Type responseDataType = response.Data.GetType();

if(responseDataType.IsArray) {
// It's an array, what to do?
}
else {
// Not an array, what's next?
}

Deserializing JSON Object Array with Json.net

You can create a new model to Deserialize your JSON CustomerJson:

    public class CustomerJson
{
[JsonProperty("customer")]
public Customer Customer { get; set; }
}

public class Customer
{
[JsonProperty("first_name")]
public string Firstname { get; set; }

[JsonProperty("last_name")]
public string Lastname { get; set; }

...
}

And you can deserialize your JSON easily:

JsonConvert.DeserializeObject<List<CustomerJson>>(json);

Documentation: Serializing and Deserializing JSON



Related Topics



Leave a reply



Submit