Rather than creating your own converter, you're going to need to create your own subclass of JsonWriter that writes to your custom file format. (This is how Json.NET implements its BsonWriter.) In your case, your file format is close enough to JSON that you can inherit from JsonTextWriter: public class...

JSON.NET doesn't support deserializing non-generic IEnumerables. CookieCollection implements IEnumerable and ICollection, but not IEnumerable<Cookie>. When JSON.NET goes to deserialize the collection, it doesn't know what to deserialize the individual items in the IEnumerable into. Contrast this with IList<Cookie> which has a generic type parameter. JSON.NET can determine what type each...

Well Json.NET 7.0.1 Beta 3 is in fact able to deal with all these cases. The key takeaway is that the deserializer must be configured for type handling as it was for serialization. I wrongly assumed that the type information available in the json file would be automatically used. May...

You need to cast Instance to a Photo first like this: var photo = wall[0].Attachments[0].Instance as Photo if (photo != null) var uri = photo.Photo604 Of course there is no error checking here. You should check for nulls and array lengths before accessing or you may get a null reference...

UPDATE - Modified code to work for any node/attribute that has value 01/01/1900. I would process XML document before conversion to JSON. Here is LinqPad example for how to do it if your date value is node or attribute value. Since I don't know your XML data structure bare with...

The JSON is an array, not an object, so deserialize it as a DataTable: var dataTable = JsonConvert.DeserializeObject<DataTable>(json); Then add the DataTable to the DataGridView using this answer: Moving data from datatable to datagridview in C#....

Microsoft time zones, such as the ones used by the TimeZoneInfo object, can indeed be serialized and deserialized, using the FromSerializedString and ToSerializedString methods. They can also be referenced with their Id property. Both of these are on the TimeZoneInfo class, not the TimeZone class (which you should not be...

Looking up System.Net.Http.Formatting we find this nugetmusthaves-page. Which in turn tells us that the assembly has a dependency which is Microsoft ASP.NET Web API 2.2 Client Libraries that in turn requires JSON.net. How did you add the System.Net.Http.Formatting assembly to your solution? Did you use nuget? Try removing it and...

The simplest thing to do would be to create a JsonConverter that adds the attribute text (which I assume corresponds to units, in this case) and attach the converter to the property: class A { [JsonConverter(typeof(UnitConverter), new object [] { "mm" })] public double? Ratio { get; set; } }...

You would have to create your own custom serialization behaviour. Have a look at this answer here : http://stackoverflow.com/a/22722467/2039359 on how to implement your own JsonConverter for Json.Net In your case you could do something like this to create your json public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)...

The easiest way to do this would be to add a get-only property for the parent id (private or public as you prefer), and serialize that, ignoring the actual Parent property: public class Category { public int id; public string name; [JsonIgnore] public Category Parent; [JsonProperty("parent", NullValueHandling = NullValueHandling.Ignore)] int?...

You're not that far off the mark. The main problem is that character_list is an array in your JSON, but the character_list property in your JsonHttp class does not represent an array or a list, so it won't deserialize properly. Here's what you need to do: First rename your character_list...

You just need to deserialise the JSON into your class. Assuming your class is called Foo, just use the JavaScriptSerializer object: Foo result = new JavaScriptSerializer().Deserialize<Foo>(json); You will need to add a reference to System.Web.Extensions in order to access the JavaScriptSerializer. EDIT Following additional clarification regarding the mapping of the...

I think that there are two different meanings of PSON here. PSON in relation to PowerShell, refers to PowerShell Object Notation. This is a format used to store PowerShell data objects in a file. One useful feature of a PSON file is that it can de-serialize itself when executed in...

You can do it with the following code string[] array = JsonConvert.DeserializeObject<String[]>("[\"String1\",\"String2\",\"String3\"]"); Here you have a complete working example using System; using Newtonsoft.Json; public class Program { public static void Main() { string[] array = JsonConvert.DeserializeObject<String[]>("[\"String1\",\"String2\",\"String3\"]"); foreach (string item in array) Console.WriteLine(item); } } Hope this helps...

This has nothing to do with the "performance" of HttpClient. The reason for this is rather that you're going 10 times to a server to get back some information. That'll be ~768ms per request, which sounds reasonable given some latency. There's little the HttpClient can do about latency and server...

In cases where JSON property names conflict with c# naming conventions, you can use DataMember or JsonProperty annotations to substitute a different name during serialization. For instance, the following works with both DataContractJsonSerializer and Json.NET: [DataContract] public class Language { [DataContract] class NamedType { [DataMember] public string name { get;...

as @dbc described in the comment, you can simply use the indexer to make this happen. var item = JObject.Parse("{ 'str1': 'test1' }"); item["str1"] = "test2"; item["str3"] = "test3"; see the fiddle for more details...

Managed to solve it. Sample code did not show that ReadabilitySettings also implemented the INotifyPropertyChanged interface. The subsequent eventhandler wired-up to the PropertyChanged event of ReadabilitySettings somewhere else in the project had some errors and thus the deserializer was not able to instantiate ReadabilitySettings :-). Not a glamorous save but...

Assuming your full JSON is as you show, your JSON doesn't give simple name/value pairs for name and email. Instead it has a dictionary of indexed property objects, where each object has a label property with value equal to the name of property you seek, and an adjacent value property...

If you would serialize this into JSON then you would get an infinite JSON-document because at the time the Serializer serializes the CTest object into JSON and he reaches the Other property this property is referenced by itself and the serializer starts with serializing this object. And so one. public...

An alternative approach would be to use an EntityHeader field in the Entity class as a backing store for private properties which can be deserialized into: public class EntityHeader { int Id { get; set; } int Checksum { get; set; } } public class Entity { private EntityHeader m_Header...

You should not parse the string for a second time, since already serialized it as JSON, you can directly use it in Javascript (the JS in JSON). var myJson = @Html.Raw(JsonConvert.Serialize(Model.MyTest)); Will output: var myJson = {"Prop1":"\"Quoted text\""}; And, because you always need a JSFiddle to prove it works....

First, to clear something up: It is my understanding that a default constructor is always created, which makes this a little hard to get my head around, could the default constructor have been specified as private, and if so why? That's not true. When you define a class with no...

Adding the converter as a JsonConverterAttribute on a class is trickier because the simplest implementation will lead to an infinite recursion as the converter calls itself. Thus it's necessary to disable the converter for recursive calls in a thread-safe manner, like so: public class NoFormattingConverter : JsonConverter { [ThreadStatic] static...

It depends on what your AJAX options are, but it looks like your object is being stringified twice before it gets sent up. You should be able to remove the stringify call: $('#description-editable form').submit(function (e) { e.preventDefault(); var data = $(this).serializeObject(); //ajax method for PUT here... }); ...

I finally went with a mix of Wrapper classes and the methodology suggested by Raphaël Althaus: use Wrappers where some amount of sophistication may be required and use Raphaël's suggestion when simplicity will do. Here's how I am using wrappers (intentionally left out null checks): public class Entity1View1 { protected...

If all you need is to extract several properties, you can just navigate the path: dynamic o = JsonConvert.DeserializeObject(json); Console.WriteLine(o.results[0].belongs_to[0].names[0].first_name); Console.WriteLine(o.results[0].belongs_to[0].names[0].last_name); Or, if you prefer string dictionaries over dynamic objects: JObject j = JsonConvert.DeserializeObject<JObject>(json); Console.WriteLine(j["results"][0]["belongs_to"][0]["names"][0]["first_name"]);...

I suggest you to create a so called anti-corruption layer. I mean, a method that converts the resulting jagged array to the desired class so the calling code will be easier to write and to read. I don't see any other solution as your json hasn't got any property name.

Clearly there is an odd runtime effect going on due to some subtle difference in behaviour between NCrunch and ReSharper. The failure is definitely telling you something is wrong and you shouldn't dismiss it as a bug in either ReSharper or NCrunch. When I step through the MSpec test in...

You have to write a custom converter for that price property (because it's not in well format), and use like this: public class Product { public string product { get; set; } [JsonConverter(typeof(MyConverter ))] public decimal[] price { get; set; } } public class MyConverter : JsonConverter { public override...

Looks like the converter for the polymorphic type is not called in this case. What you can do instead is to create your YetAnotherConverter; in ReadJson load the object into a JToken, parse the "$type" property, then call JToken.ToObject(type, serializer) to deserialize the intermediate JToken to your final type. This...

You could try CloudBlockBlob.DownloadText method to download the blob contents as text and then use Json.Net's JsonConvert to serialize the string into your customer object. For example, something like the following: var customerData = blob.DownloadText(); var customer = JsonConvert.DeserializeObject<Customer>(customerData); ...

This is a bug in JSON.NET as hinted at, but it's not as simple as it first seems. Versions prior to 5.0.4 work for both of these test cases. Anything after seems to fail but only for the first test case which is odd. I've gone through some of the...

I would recommend simply making the converted GUID be a private get-only property on the containing class. If you mark it with [JsonProperty] it will be serialized: public class Outer { public int Id { get; set; } public Guid? ProductFamilyId { get; set; } [JsonProperty(NullValueHandling=NullValueHandling.Ignore)] Guid? OldProductFamilyId { get...

Because the type of deserializedData["key"] is Int64 (you'll see when you debug). You can't cast Int64 to int (Int32) . what you can do: int value = System.Convert.ToInt32(deserializedData["key"]); ...

The solution to this problem is to configure the deserializer to use the type information in the json. It is not used by default. Serialization is done this way : Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer(); serializer.Converters.Add(new Newtonsoft.Json.Converters.JavaScriptDateTimeConverter()); serializer.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore; serializer.TypeNameHandling = Newtonsoft.Json.TypeNameHandling.Auto; serializer.Formatting = Newtonsoft.Json.Formatting.Indented; using...

I ended up going with a solution using the JToken.Parse method in the Json.NET library. Essentially what is happening is that we check the top level properties of the JSON object and see if there exists the current action parameter we are trying to bind to. Where this falls down...

What you have here is a hierarchical dictionary of named properties, where each property can have a type, a format, and possibly a nested dictionary of named child properties -- metadata in your case. You can represent this with the following data model: [DataContract] public class PropertyData { [DataMember(Name="type", EmitDefaultValue=false)]...

Each element in your array is just another string - so you need to parse each of those as well. For example: IList<Page> pages = jsonArray .Select(text => JObject.Parse(text)) .Select(p => new Page { ... }) .ToList(); Alternatively, change your Javascript code to avoid the double-encoding, so you end up...

You have to parse json text as RootObject, then access Result objects through results property. I've copied your text, appended closing braces "}" at the end and saved to file. Everything seems to work. using System; using System.Collections.Generic; using System.IO; using Newtonsoft.Json; namespace ConsoleApplication2 { class Program { static void...

Another way to find null/undefined tokens during De-serialization is to write a custom JsonConverter , Here is an example of custom converter which can report both omitted tokens (e.g. "{ 'Id':5 }") and null tokens (e.g {"Id":5,"SomeString":null,"SomeInt":null}) public class NullReportConverter : JsonConverter { private readonly List<PropertyInfo> _nullproperties=new List<PropertyInfo>(); public bool...

Create a custom converter. Something like this: public class StringToIntEnumerable : JsonConverter { public override bool CanConvert(Type objectType) { throw new NotImplementedException(); } public override bool CanWrite { get { return false; // we'll stick to read-only. If you want to be able // to write it isn't that much...

One simple way to get it working is to use the JsonProperty attribute to specify what JSON key you want to map to a certain C# property: public class Schedule { [JsonProperty("schedule.ID")] public int ID {get;set;} [JsonProperty("schedule.Name")] public string Name {get;set;} } Then you can just use JsonConvert.DeserializeObject to deserialize...

The Json string you presented isn't a deserialised DataTable so you can't convert it into that object type directly. Not really sure if you absolutely need for this to be a DataTable, but if you do then here is a way. You can first get it into an array of...

It is correct JSON in a sense that it's valid, but it's clearly not what you want. So the answer depends on the definition of "correct". We will assume that what you want is "correct". You're asking it to aggregate u, which is a resultset with column team. This means...

Since AppSettings is a NameValueCollection, you cannot convert it directly to Json. You should populate a Dictionary from it and serialize it using the JsonConvert class: Dictionary<string, string> items = new Dictionary<string, string>(); foreach (string key in ConfigurationManager.AppSettings) { string value = ConfigurationManager.AppSettings[key]; items.Add(key, value); } string json = JsonConvert.SerializeObject(items,...

I believe your intent would be the following: private DateTime? date; public DateTime? Date { get { if(date != null) return TimeZoneInfo.ConvertToUtc(date); return date; } } That would create a Property that will take a date format, then will convert it to a valid UTC Format. However, if you require...

The basic difficulty here is that Json.NET is a contract-based serializer which creates a contract for each type to be serialized, then (de)serializes according to the contract. If a type appears in multiple locations in the object hierarchy, the same contract applies. But you want to selectively include properties for...

OK, it was fixed in Json.NET 4.0.1: Fixed JToken Load and Parse methods not checking for incomplete content, but your're stuck on 35r8 because that's the last version that supports the compact framework. In that case, the following static helper methods will check that the start and end depths match:...

You do not need nested generic collections if you use Json.NET 5.0 release 5 or later version. You can use JsonExtensionDataAttribute so that Item dictionary's keys and values will be serialized as a part of parent object. public class ReferenceData { public string version { get; set; } public List<DataItem>...

You can just use indexer: foreach (var element in facebook["posts"]["data"]) { message = element["message"]; image = element["image"]; //etc } Here is an example, and by the way your JSON is invalid......

I see a few issues here. First, your JSON is not valid; it appears to be only a fragment. Valid, complete JSON would look like the following. (I added enclosing braces, removed the trailing comma and balanced the braces for the payment_info object.) { "payment_info": { "fb_id": "", "order_items": {...

Thanks for all the help, I've managed to get it doing what I want which is de-serializing individual location objects. If the item is converted to a JObject it will read in the full object and de-serialize it, this can be looped to get the solution. This is the code...

It looks like you're not adding the rows to the table so when the binding takes place, there's no data. This should fix that problem: for (int i = 0; i < jsonItemData.Count; i++) { DataRow dtRow = dtInventory.NewRow(); dtRow["ItemID"] = sItemID.ToString(); dtRow["ItemImageUrl"] = jsonItemData[sItemID]["icon_url"].ToString(); dtRow["ItemName"] = jsonItemData[sItemID]["market_name"].ToString(); dtRow["Tradeable"] =...

This appears to be a bug with CamelCasePropertyNamesContractResolver. Its base class, DefaultContractResolver, has two constructors: a parameterless constructor, and a DefaultContractResolver (Boolean) version (just made obsolete in Json.NET 7.0). This parameter has the following meaning: shareCache Type: System.Boolean If set to true the DefaultContractResolverwill use a cached shared with other...