# fastJSON

By , 19 Apr 2013

## Preface

The code is now on CodePlex at http://fastjson.codeplex.com/ . I will do my best to keep this article and the source code on CodePlex in sync.

## Introduction

This is the smallest and fastest polymorphic JSON serializer, smallest because it's only 25kb when compiled, fastest because most of the time it is (see performance test section) and polymorphic because it can serialize and deserialize the following situation correctly at run-time with what ever object you throw at it:

class animal { public string Name { get; set;} }
class cat: animal { public int legs { get; set;} }
class dog : animal { public bool tail { get; set;} }
class zoo { public List<animal> animals { get; set;} }

var zoo1 = new zoo();

zoo1.animals = new List<animal>();


This is a very important point because it simplifies your coding immensely and is a cornerstone of object orientated programming, strangely few serializers handle this situation, even the  XmlSerializer in .NET  doesn't do this and you have to jump through hoops to get it to work. Also this is a must if you want to replace the BinaryFormatter serializer which what most transport protocols use in applications and can handle any .NET object structure (see my WCF Killer article).

## The What and Why of JSON

JSON (Java Script Object Notation) is a text or human readable format invented by Douglas Crockford around 1999 primarily as a data exchange format for web applications (see www.JSON.org). The benefits of which are ( in regards to XML which was used before):

• Structured data format like XML
• High signal to noise ratio in other words it does away with extra characters which are not conclusive to the data ( angle brackets and slashes in XML)
• Compact data format
• Simple parsing rules which makes the processing of data easy and fast

So its good for the following scenarios:

• Data exchange between same or different platforms like Java, .NET services over the wire.
• Data storage: MongoDB (www.mongodb.org) uses JSON as an internal storage format.

## Features of this implementation

• Just 3 classes + 2 helpers : 1158 lines of code
• JSON standard compliant with the following additions
• "$type" is used to denote object type information [ Json.NET does this as well ]. • "$schema" is used to denote the dataset schema information
• "$map" is used for post processing runtime types when assigned to the object type. • "$types" is used for global type definition where the instances reference this dictionary of types via a number ( reduces JSON size for large number of embedded types)
• Works on .NET 2.0+ : some implementations in the list of alternatives below require at least .NET 3.5
• Extremely small size : 25kb when compiled
• Blazingly fast (see the performance tests section)
• Can dynamically create types
• Handles Guid, Dataset, Dictionary, Hashtable and Generic lists
• Handles Nullable types
• Handles byte arrays as base64 strings
• Handles polymorphic collections of objects
• Handles value type arrays (e.g. int[] char[] etc.)
• Handles value type generic lists (e.g. List<int> etc.)
• Handles special case List<object[]> (useful for bulk data transfer)
• Handles Embedded Classes (e.g. Sales.Customer)
• Handles polymorphic object type deserialized to original type (e.g object ReturnEntity = Guid, DataSet, valuetype, new object[] { object1, object2 } ) [needed for wire communications].
• Ability to disable extensions when serializing for the JSON purists (e.g. no $type, $map in the output).
• Ability to deserialize standard JSON into a type you give to the deserializer, no polymorphism is guaranteed.
• Special case optimized output for Dictionary<string,string>.
• Override null value outputs.
• Handles XmlIgnore attributes on properties.
• Datatable support.
• Indented JSON output via IndentOutput property.
• Support for SilverLight 4.0+.
• RegisterCustomType() for user defined and non-standard types that are not built into fastJSON (like TimeSpan, Point, etc.).
• This feature must be enabled via the CUSTOMTYPE compiler directive as there is about a 1% performance hit.
• You supply the serializer and deserializer routines as delegates.
• Added support for public Fields.
• Added ShowReadOnlyProperties to control the output of readonly properties (default is false = won't be outputted).
• Automatic UTC datetime conversion if the date ends in "Z" (JSON standard compliant now).
• Added UseUTCDateTime property to control the output of UTC datetimes.
• Dictionary<string, > are now stored optimally not in K V format.
• Support for Anonymous Types in the serializer (deserializer is not possible at the moment)

### Limitations

• Currently can't deserialize value type array properties (e.g. int[] char[] etc.)
• Currently can't handle multi dimensional arrays.
• Silverlight 4.0+ support lacks HashTable, DataSet, DataTable as it is not part of the runtime.

## What's out there

In this section I will discuss some of the JSON alternatives that I have personally used. Although I can't say it is a comprehensive list, it does however showcase the best of what is out there.

### XML

If you are using XML, then don't. It's too slow and bloated, it does deserve an honorable mention as being the first thing everyone uses, but seriously don't. It's about 50 times slower than the slowest JSON in this list. The upside is that you can convert to and from JSON easily.

### BinaryFormatter

Probably the most robust format for computer to computer data transfer. It has a pretty good performance although some implementation here beat it.

 Pros Cons Can handle anything with a Serializable attribute on itPretty compact output Version unfriendly : must be deserialized into the exact class that was serialized Not good for storing of data because of the versioning problemNot human readableNot for communication outside of the same platform (e.g. both sides must be .NET)

### Json.NET

The most referenced JSON serializer for the .NET framework is Json.NET from (http://JSON.codeplex.com/) and the blog site (http://james.newtonking.com/pages/JSON-net.aspx). It was the first JSON implementation I used in my own applications.

 Pros Cons Robust output which can handle datasetsFirst implementation I saw which could handle polymorphic object collections Large dll size ~320kbSlow in comparison to the rest in the listSource code is hard to follow as it is large

### LitJSON

I had to look around a lot to find this gem (http://litjson.sourceforge.NET/), which is still at version 0.5 since 2007. This was what I was using before my own implementation and it replaced the previous JSON serializer which was Json.NET. Admittedly I had to change the original to fit the requirements stated above.

 Pros Cons Can do all that Json.NET does (after my changes).Small dll size ~57kb Relatively fast Didn't handle datasets in the original source code ( I wrote it my self afterwards in my own application)The lexer class is difficult to followRequires .NET 3.5 ( Got around this limitation by implementing a Linqbridge class which works with .NET 2.0)

### ServiceStack Serializer

An amazingly fast JSON serializer from Demis Bellot found at (http://www.servicestack.NET/mythz_blog/?p=344). The serializer speed is astonishing, although it does not support what is needed from the serializer. I have included it here as a measure of performance.

 Pros Cons Amazingly fast serializerPretty small dll size ~91kb Can't handle polymorphic object collectionsRequires at least .NET 3.5Fails on Nullable typesFails on Datasets Fails on other "exotic" types like dictionaries, hash tables etc.

### Microsoft Json Serializer  (v1.7 update)

By popular demand and my previous ignorance about the Microsoft JSON implementation and thanks to everyone who pointed this out to me, I have added this here.

Pros      Cons
• Included in the framework
• Can serialize basic polymorphic objects
• Can't deserialize polymorphic objects
• Fails on Datasets
• Fails on other "exotic" types like dictionaries, hash tables etc.
• 4x slower that fastJSON in serialization

## Using the code

To use the code do the following:

// to serialize an object to string
string jsonText = fastJSON.JSON.Instance.ToJSON(c);

// to deserialize a string to an object
var newobj = fastJSON.JSON.Instance.ToObject(jsonText);

The main class is JSON which is implemented as a singleton so it can cache type and property information for speed.

// you can set the defaults for the Instance which will be used for all calls
JSON.Instance.UseOptimizedDatasetSchema = true; // you can control the serializer dataset schema
JSON.Instance.UseFastGuid = true;               // enable disable fast GUID serialization
JSON.Instance.UseSerializerExtension = true;    // enable disable the $type and$map inn the output

// you can do the same as the above on a per call basis
public string ToJSON(object obj, bool enableSerializerExtensions)
public string ToJSON(object obj, bool enableSerializerExtensions, bool enableFastGuid)
public string ToJSON(object obj, bool enableSerializerExtensions, bool enableFastGuid, bool enableOptimizedDatasetSchema)

// Parse will give you a Dictionary<string,object> with ArrayList representation of the JSON input
public object Parse(string json)

// if you have disabled extensions or are getting JSON from other sources then you must specify
// the deserialization type in one of the following ways
public T ToObject<T>(string json)
public object ToObject(string json, Type type)

JSON.Instance.SerializeNullValues = true;    // enable disable null values to output

public string ToJSON(object obj, bool enableSerializerExtensions, bool enableFastGuid, bool enableOptimizedDatasetSchema, bool serializeNulls)


For all those who requested why there is no support for type "X", I have implemented a open closed principal extension to fastJSON which allows you to implement your own routines for types not supported without going through the code.

To allow this extension you must compile with CUSTOMTYPE compiler directive as there is a performance hit associated with it.

public void main()
{
fastJSON.JSON.Instance.RegisterCustomType(typeof(TimeSpan), tsser, tsdes);
// do some work as normal
}

private static string tsser(object data)
{
return ((TimeSpan)data).Ticks.ToString();
}

private static object tsdes(string data)
{
return new TimeSpan(long.Parse(data))
}


## Performance Tests

All test were run on the following computer:

• AMD K625 1.5Ghz Processor
• 4Gb Ram DDR2
• Windows 7 Home Premium 64bit
• Windows Rating of 3.9

The tests were conducted under three different .NET compilation versions

• .NET 3.5
• .NET 4 with processor type set to auto
• .NET 4 with processor type set to x86

The Excel screen shots below are the results of these test with the following descriptions:

• The numbers are elapsed time in milliseconds.
• The more red the background the slower the times
• The more green the background the faster the times.
• 5 tests were conducted for each serializer.
• The "AVG" column is the average for the last 4 tests excluding the first test which is basically the serializer setting up its internal caching structures, and the times are off.
• The "min" row is the minimum numbers in the respective columns below.
• The Json.NET serializer was tested with two version of 3.5r6 and 4.0r1 which is the current one.
• "bin" is the BinaryFormatter tests which for reference.
• The test structure is the code below which is a 5 time loop with an inner processing of 1000 objects.
• Some data types were removed from the test data structure so all serializers could work.

### The test code template

The following is the basic test code template, as you can see it is a loop of 5 tests of what we want to test each done count time (1000 times). The elapsed time is written out to the console with tab formatting so you can pipe it to a file for easier viewing in an Excel spreadsheet.

int count = 1000;
private static void fastjson_serialize()
{
Console.WriteLine();
Console.Write("fastjson serialize");
for (int tests = 0; tests < 5; tests++)
{
DateTime st = DateTime.Now;
colclass c;
string jsonText = null;
c = CreateObject();
for (int i = 0; i < count; i++)
{
jsonText = fastJSON.JSON.Instance.ToJSON(c);
}
Console.Write("\t" + DateTime.Now.Subtract(st).TotalMilliseconds + "\t");
}
}

### The test data structure

The test data are the following classes which show the polymorphic nature we want to test. The "colclass" is a collection of these data structures. In the attached source files more exotic data structures like Hashtables, Dictionaries, Datasets etc. are included.

[Serializable()]
public class baseclass
{
public string Name { get; set; }
public string Code { get; set; }
}

[Serializable()]
public class class1 : baseclass
{
public Guid guid { get; set; }
}

[Serializable()]
public class class2 : baseclass
{
public string description { get; set; }
}

[Serializable()]
public class colclass
{
public colclass()
{
items = new
List<baseclass>();
date = DateTime.Now;
multilineString = @"
ahjksjkAHJKS
AJKHSKJhaksjhAHSJKa
AJKSHajkhsjkHKSJKash
ASJKhasjkKASJKahsjk
";
gggg = Guid.NewGuid();
//hash = new Hashtable();
isNew = true;
done= true;
}
public bool done { get; set; }
public DateTime date {get; set;}
//public DataSet ds { get; set; }
public string multilineString { get; set; }
public List<baseclass> items { get; set; }
public Guid gggg {get; set;}
public decimal? dec {get; set;}
public bool isNew { get; set; }
//public Hashtable hash { get; set; }

}

### .NET 3.5 Serialize

• fastJSON is second place in this test by a margin of nearly 35% slower than Stacks.
• fastJSON is nearly 2.9x faster than binary formatter.
• Json.NET is nearly 1.9x slower in the new version 4.0r1 against its previous version of 3.5r6
• Json.NET v3.5r6 is nearly 20% faster than binary formatter.

### .NET 3.5 Deserialize

• fastJSON is first place in this test to Stacks by a margin of 10%.
• fastJSON is nearly 4x faster than nearest other JSON.
• Json.NET is nearly 1.5x faster in version 4.0r1 than its previous version of 3.5r6

### .NET 4 Auto Serialize

• fastJSON is first place in this test by a margin of nearly 20% against Stacks.
• fastJSON is nearly 4.9x faster than binary formatter.
• Json.NET v3.5r6 is on par with binary formatter.

### .NET 4 Auto Deserialize

• fastJSON is first place by a margin of 11%.
• fastJSON is 1.7x faster than binary formatter.
• Json.NET v4 1.5x faster than its previous version.

### .NET 4 x86 Serialize

• fastJSON is first place in this test by a margin of nearly 21% against Stacks.
• fastJSON is 4x faster than binary formatter.
• Json.NET v3.5r6 1.7x faster than the previuos version.

### .NET 4 x86 Deserialize

• fastJSON is first place by a margin of 5% against Stacks.
• fastJSON is 1.7x faster than binary formatter which is third.

### Exotic data type tests

In this section we will see the performance results for exotic data types like datasets, hash tables, dictionaries, etc.. The comparison is between fastJSON and the BinaryFormatter as most of the other serializers can't handle these data types. These include the following:

• Datasets
• Nullable types
• Hashtables
• Dictionaries

• fastJSON is 5x faster than BinaryFormatter in serialization
• fastJSON is 20% faster than BinaryFormatter in deserialization
• Datasets are performance killers by a factor of 10

## Performance Conclusions

• fastJSON is faster in all test except the when running the serializer under .NET 3.5 for which Stacks is faster by only 35% (note must be made that Stacks is not polymorphic and can't handle all types so it is not outputting data correctly within the tests).
• .NET 4 is faster than .NET 3.5 by around 15% in these test except for the fastJSON serializer which is 90% faster..
• You can replace BinaryFormatter with fastJSON with a huge performance boost ( this lean way lends it self to compression techniques on the text output also).
• Start up costs for fastJSON is on average 2x faster than Stacks and consistently faster than everyone else.

## Performance Conclusions v1.4

As you can see from the above picture v1.4 is noticably faster. The speed boost make fastJSON faster than SerializerStack in all tests even on .net v3.5.

• fastJSON serializer is 6.7x faster than binary with a dataset.
• fastJSON deserializer is 2.1x faster than binary with a dataset.
• fastJSON serializer is 6.9x faster than binary without a dataset.
• fastJSON deserializer is 1.6x faster than binary without a dataset.

## Performance Conclusions v1.5

• The numbers speak for themselves fastJSON serializer 6.65x faster without dataset and 6.88x faster than binary, the deserializer is 2.7x faster than binary.
• The difference in numbers in v1.5 which is slower than v1.4 is because of extra properties in the test for Enums etc.

## Performance Conclusions v1.6

• Guid are 2x faster now with base64 encoding you can revert back to old style with the UseFastGuid = false on the JSON.Instance
• Datasets are ~40% smaller and ~35% faster.
• fastJSON serializer is now ~2.3x faster than deserializer and the limit seems to be 2x.

## Performance Conclusions v1.7

• int, long parse are 4x faster.
• unicode string optimizations, reading and writing non english strings are faster.
• ChangeType method optimized
• Dictionary optimized  using TryGetValue

## Points of Interest

I did a lot of performance tuning with a profiler and here are my results:

• Always use a StringBuilder and never strings concats.
• Never do the following stringbuilder.append("string1 + "string2") because it kills performance, replace it with two stringbuilder appends. This point blew my mind and was 50% faster in my tests with the profiler.
• Never give the stringbuilder a capacity value to start with e.g. var stringbuilder = new StringBuilder(4096); . Strange but it is faster without it.
• I tried replacing the StringBuiler with a MemoryStream but it was too slow (100% slower).
• The simplest and the most direct way is probably the fastest as well, case in point reading values as opposed to lexer parser implementations.
• Always use cached reflection properties on objects.

## Appendix v1.9.8

Some reformatting was done to make the use of fastJSON easier in this release which will break some code but is ultimately better in the long run. To use the serializer in this version you can do the following :

// per call customization of the serializer
string str = fastJSON.JSON.Instance.ToJSON(obj,
new fastJSON.JSONParamters { EnableAnonymousTypes = true }); // using the parameters

fastJSON.JSON.Instance.Parameters.UseExtensions = false; // set globally


This removes a lot of the ToJSON overloads and gives you more readable code.

Also in this release support for anonymous types has been added, this will give you a JSON string for the type, but deserialization is not possible at the moment since anonymous types are compiler generated.

DeepCopy has been added which allows you to create an exact copy of your objects which is useful for business application rollback/cancel semantics.

## Appendix v2.0.0

Finally got round to adding Unit Tests to the project (mostly because of some embarrassing bugs that showed up in the changes), hopefully the tests cover the majority of use cases, and I will add more in the future.

Also by popular demand you can now deseialize root level basic value types, Lists and Dictionaries. So you can use the following style code :

var o = fastJSON.JSON.Instance.ToObject<List<Retclass>>(s); // return a generic list

var o = fastJSON.JSON.Instance.ToObject<Dictionary<Retstruct, Retclass>>(s); // return a dictionary


A breaking change in this version is the Parse() method now returns number formats as long and decimal not string values, this was necessary for array returns and compliance with the json format (keep the type information in the original json, and not loose it to strings).  So the following code is now working :

List<int> ls = new List<int>();
ls.AddRange(new int[] { 1, 2, 3, 4, 5, 10 });
var s = fastJSON.JSON.Instance.ToJSON(ls);
var o = fastJSON.JSON.Instance.ToObject(s); // long[] {1,2,3,4,5,10}


Be aware that if you do not supply the type information the return will be longs not ints.  To get what you expect use the following style code:

var o = fastJSON.JSON.Instance.ToObject<List<int>>(s); // you get List<int>

Check the unit test project for sample code regarding the above cases.

## Appendix v2.0.3 -  Silverlight Support

Microsoft in their infinate wisdom has removed some functionality which was in Silverlight4 from Silverlight5. So fastJSON will not build or work on Silverlight5.

## Appendix v2.0.10 - MonoDroid Support

In this release I have added a MonoDroid project file and fastJSON now compiles and works on Android devices running the excellent work done by Miguel de Icaza and his team at Xamarin. This is what Silverlight should have been and I am really excited about this as it will open a lot of opportunities one of which is the new RaptorDB

## Appendix v2.0.11 - Unicode Changes

My apologies to everyone regarding my misreading of the JSON standard regarding Unicode, my interpretation was that the output should be in ASCII format and hence all non ASCII characters should be in the \uxxxx format.

In this version you can control the output format with the UseEscapedUnicode parameter and all the strings will be in Unicode format (no \uxxxx), the default is true for backward compatibility.

## Appendix - fastJSON vs Json.net rematch

After being contacted by James Newton King for a retest with his new version of Json.net which is v5r2, I redid the tests and here is the results (times are in milliseconds):

As you can see there are 5 test and the AVG column is the average of the last 4 tests so to exclude the startup of each library, the DIFF column is the difference between the two libraries and fastJSON being the base of the test.

Things to note :

• fastJSON is about 2x faster than Json.net in both serialize and deserialize.
• Json.net is about 1.5-2x faster that it's previous versions which is a great job of optimizatons done and congratualtions in order.

## History

• Initial Release : 2011/02/20
• Update v1.1 : 26% performance boost on dataset deserialization, corrected ServiceStack name
• Update v1.2 : System.DBNull serialized to null, CultureInfo fix for numbers, Readonly properties handled correctly
• Update v1.3 : Removed unused code (lines now at 780), Property comma fix
• Update v1.4 : Heavy optimizations (serializer 3% faster, deserializer  50% faster, dataset serializer 46% faster, dataset deserializer 26% faster) [ now officially faster than the serializer ServiceStack in all test even on .net 3.5]
• Update v1.5 : Heavy optimizations (deserializer ~50% faster than v1.4), Enum fix, Max Depth property for serializer. Special thanks and credits to Simon Hewitt for optimizations in this version.
• Update v1.6 :
• value type arrays handled
• guid 2x faster
• datasets ~40% smaller
• serializer ~2% to 11% faster
• deserializer ~6% to 38% faster
• Update v1.7 :
• bug fix dictionary deserialize
• special case handles List<object[]>
• int and long parse 4x faster
• unicode string optimize
• changetype optimize
• dictionary optimize
• deserialize embeded class e.g. Sales.Customer
• handles object ReturnEntity = new object[] { object1, object2 }
• handles object ReturnEntity = Guid, Dataset, valuetype
• Update v1.7.5 :
• ability to serialize without extensions
• overloaded methods for serialize and deserialize
• the deserializer will do its best to deserialize the input with or without extensions with no gaurantee on polymorphism
• Update v1.7.6 :
• XmlIgnore handled : thanks to Patrik Oscarsson for the idea
• special case optimized output for dictionary of string,string
• bug fix year 1 date output as 0000 string
• override serialize nulls to output : thanks again to Patrik
• Update v1.7.7 :
• Indented output
• Datatable support
• bug fix
• Update v1.7.7 Silverlight4 : 4th June 2011
• A new project added for silverlight4, currently in testing phase will add to main zip when all ok.
• Silverlight lacks arraylist, dataset, datatable, hashtable support
• #if statements in source files for silverlight4 support.
• Update v1.8 :  9th June 2011
• Silverlight code merged into the project
• Seperate Silverlight project
• RegisterCustomType extension for user defined serialization routines
• CUSTOMTYPE compiler directive
• Update v1.9 : 28th June 2011
• added support for public fields
• Update v1.9.1 : 30th June 2011
• fixed a shameful bug when SerializeNullValues = false, special thanks to Grant Birchmeier for testing
• Update v1.9.2 : 10th July 2011
• fixed to fullname instead of name when searching for types in property cache (namespace1.myclass , namespace2.myclass are now different) thanks to alex211b
• Update v1.9.3 : 31st July 2011
• UTC datetime handling via UseUTCDateTime = true property thanks to mrkappa
• added support for enum as key in dictionary thanks to Grant Birchmeier
• Update v1.9.4 : 23rd September 2011
• if datetime value ends in "Z" then automatic UTC time calculated
• if using UTC datetime the output end in a "Z" (standards compliant)
• Update v1.9.6 : 26th November 2011
• bug fix datatable schema serialize & deserialize
• added a $types extension for global type definitions which reduce the size of the output json thanks to Marc Bayé for the idea • added UsingGlobalTypes config for controling the above (default = true) • bug fix datatable commas between arrays and table definitions (less lint complaining) • string key dictionaries are serialized optimally now (not K V format) • Update v1.9.7 : 10th May 2012 • bug fix SilverLight version to support GlobalTypes • removed indent logic from serializer • added Beautify(json) method to JSON credits to Mark http://stackoverflow.com/users/65387/mark • added locks on SafeDictionary • added FillObject(obj,json) for filling an existing object • Update v1.9.8 : 17th May 2012 • added DeepCopy(obj) and DeepCopy<T>(obj) • refactored code to JSONParameters and removed the JSON overloads • added support to serialize anonymous types (deserialize is not possible at the moment) • bug fix$types output with non object root
• Update v1.9.9 : 24th July 2012
• spelling mistake on JSONParameters
• bug fix Parameter initialization
• bug fix char and string ToString
• refactored reflection code into Reflection class
• added support for top level struct object serialize/deserialize
• Update v2.0.0 : 4th August 2012
• bug fix reflection code
• deserialize root level arrays (int[] etc.)
• deserialize root level value types (int,long,decimal,string)
• deserialize ToObject< Dictionary<T,V> >
• deserialize ToObject< List<T> >
• * breaking change in Parse , numbers are returned as decimals and longs not strings
• Update v2.0.1 : 10th August 2012
• bug fix preserve internal objects when FillObject called
• changed ArrayList to List<object> and consolidated silverlight code
• speed increase when using global types ($types) • Update v2.0.2 : 16th August 2012 • bug fix$types and arrays
• Update v2.0.3 : 27th August 2012
• readonly property checking on deserialize (thanks to Slava Pocheptsov)
• bug fix deserialize nested types with unit test (thanks to Slava Pocheptsov)
• fix the silverlight4 project build (silverlight5 is not supported)
• Update v2.0.4 : 7th September 2012
• fixed null objects -> returns "null"
• added sealed keyword to classes
• bug fix SerializeNullValues=false and an extra comma at the end
• UseExtensions=false will disable global types also  (thanks to qio94, donat.hutter, softwarejaeger)
• fixed parameters setting for Parse()
• Update v2.0.5 : 17th September 2012
• fixed number parsing for invariant format
• added a test for German locale number testing (,. problems)
• Update v2.0.6 : 19th September 2012
• singleton uses [ThreadStatic] for concurrency (thanks to Philip Jander)
• bug fix extra comma in the output when only 1 property in the object (thanks to Philip Jander)
• Update v2.0.7 : 5th October 2012
• bug fix missing comma with single property and extensions enabled
• Update v2.0.8 : 13th October 2012
• bug fix big number conversions  (thanks to  Alex .µZ Hg.
• * breaking change Parse will return longs and doubles instead of longs and decimal
• ToObject on value types will auto convert the data (e.g ToObject<decimal>() )
• Update v2.0.9 : 24th October 2012
•  added support for root level DataSet and DataTable deserialize (you have to do ToObject<DataSet>(...) )
• Update v2.0.10 : 15th November 2012
• Update v2.0.11 : 7th December 2012
• bug fix single char number json
• added UseEscapedUnicode parameter for controlling string output in \uxxxx for unicode/utf8 format
• bug fix null and generic ToObject<>()
• bug fix List<> of custom types
• Update v2.0.12 : 3rd January 2013
• bug fix nested generic types (thanks to Zambiorix)
• bug fix comma edge cases with nulls
• Update v2.0.13 : 9th January 2013
• bug fix comma edge cases with nulls
• unified DynamicMethod calls with SilverLight4 code
• test cases for silverlight
• Article Update : 12th April 2013
• rematch between fastJSON and Json.net v5r2
• Update v2.0.14 : 19th April 2013
•   Optimizations done by Sean Cooper
- using Stopwatch instead of DateTime for timings
- myPropInfo using enum instead of boolean
- parsing DateTime optimized
- StringBuilder using single char output instead of strings for \" chars etc

 Mehdi Gholam Architect United Kingdom Member
Mehdi first started programming when he was 8 on BBC+128k machine in 6512 processor language, after various hardware and software changes he eventually came across .net and c# which he has been using since v1.0.
He is formally educated as a system analyst Industrial engineer, but his programming passion continues.

* Mehdi is the 5th person to get 6 out of 7 Platinums on CodeProject (13th Jan'12)

Votes of 3 or less require a comment

 Search this forum Profile popups    Spacing RelaxedCompactTight   Noise Very HighHighMediumLowVery Low   Layout Open AllThread ViewNo JavascriptPreview   Per page 102550
 Encoding of special characters Member 9595122 20 Nov '12 - 3:24
 hi Mehdi,   i'm converting values with special characters (i.e. German Umlaut, etc.) from Objects to Json. The problem is now, that those values are converted to utf-8 escaped character (i.e. ü ==> \\u00FC).   I was wondering, why those characters are escaped and if there's a way around it, without converting it after the serialization.   thanks for your help, Chris Sign In·View Thread·Permalink
 Re: Encoding of special characters Mehdi Gholam 20 Nov '12 - 4:46
 The JSON standard states that all non-ASCII characters should be escaped like that. Its the man, not the machine - Chuck Yeager If at first you don't succeed... get a better publicist If the final destination is death, then we should enjoy every second of the journey. Sign In·View Thread·Permalink
 Re: Encoding of special characters Dimitris Krikris 2 Dec '12 - 11:57
 For some weird reason even what you say is true   i have the following situation...   var jsonText = "{\"some_number\": 108.541,\"date_time\": \"2011-04-13T15:34:09Z\", \"serial_number\": \"ασδασδα\",\"more_data\": {\"field1\": 1.0, \"field2\": \"hello\"}}"; var dict = (Dictionary)fastJSON.JSON.Instance.Parse(json); textbox1.Text = fastJSON.JSON.Instance.ToJSON(dict);   The textbox displays \u chars for the greek chars i put in serial_number. The problem is that if i send that json object to a php Rest API the stored mysql string does not display greek but rather japanese at best. I happened to get json from that same rest api and my client displayed weird characters also (NOT ALWAYS though ??? i cannot seem to replicate, sometimes i see greek characters even though phpmyadmin displays Glyphs and sometimes i see Glyphs).   While using either System.Web.Script.Serialization.JavaScriptSerializer or Newtonsoft.Json both the textbox and phpmyadmin display the greek characters properly.   I really hope you can fix this. Sign In·View Thread·Permalink
 Re: Encoding of special characters Mehdi Gholam 2 Dec '12 - 19:10
 fastJSON does not have any problem deserializing the string you provided (with non ascii characters) and you should use ToObject() instead of Parse() if you want the object structure, Parse should be used when you don't know the structure or the container object beforehand.   Serialize is a different matter, currently fastJSON outputs in ascii format and all non ascii characters are escaped as \uxxxx (>32 and <128), the php side probably does not implement parsing \uxxxx chars.   Having said the above, I have contacted Master Crockford for clarification regarding UTF8/Unicode string defaults, I will post back when I get an answer. Its the man, not the machine - Chuck Yeager If at first you don't succeed... get a better publicist If the final destination is death, then we should enjoy every second of the journey. Sign In·View Thread·Permalink
 Re: Encoding of special characters Dimitris Krikris 3 Dec '12 - 0:50
 I am currently at work and i don't have access to my code. I tested fastJSON Serialize and it produces the same result as what the server hands me over (that was previously serialized with Json.NET).   I am really at a loss. Either the Streamwriter.Write(json) does something internally that i am not aware of and the php backend manages to parse it and send it to mysql as normal or i have no idea whatsoever what may be the case. Since the server sends me the same json result in fastJSON or json.net or system.web.   Since it happened at some point and the result was displayed not as intended using fastJSON i really cannot continue using it until the problem is resolved. You do realize that "some point" in computer science cannot be taken lightly (i.e. it was just one time and the likes...)   I am using fastJSON in most cases due to speed and mostly because of the code being that small. Sign In·View Thread·Permalink
 Re: Encoding of special characters Mehdi Gholam 3 Dec '12 - 1:07
 I have created a JSONParameters.UseEscapedUnicode which will control the unicode output so this should work for you.   I will post this soon (testing at the moment )   Thanks. Its the man, not the machine - Chuck Yeager If at first you don't succeed... get a better publicist If the final destination is death, then we should enjoy every second of the journey. Sign In·View Thread·Permalink
 Re: Encoding of special characters Mehdi Gholam 3 Dec '12 - 1:13
 Make sure you are using Encoding on your streams : http://msdn.microsoft.com/en-us/library/3aadshsx.aspx[^] Its the man, not the machine - Chuck Yeager If at first you don't succeed... get a better publicist If the final destination is death, then we should enjoy every second of the journey. Sign In·View Thread·Permalink
 Re: Encoding of special characters [modified] Dimitris Krikris 3 Dec '12 - 5:56
 Ok i seems to be working just fine in those 2 situations...   Either by using...   StreamWriter sw = new StreamWriter(request.GetRequestStream(),Encoding.ASCII); sw.Write(json); sw.Close(); with the default output.   or... private static Regex DECODING_REGEX = new Regex(@"\\u(?[a-fA-F0-9]{4})", RegexOptions.Compiled); private const string PLACEHOLDER = @"#!#";   public static string DecodeEscaped( string value ) { return DECODING_REGEX.Replace( value.Replace(@"\\", PLACEHOLDER), m => { return ((char)int.Parse(m.Groups["Value"].Value, NumberStyles.HexNumber)).ToString(); }) .Replace(PLACEHOLDER, @"\\"); }   public static string httpPost(string api,string json) { json = DecodeEscaped(json); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(host+api); request.Method = "POST"; request.ContentType = "application/json"; //request.ContentLength = json.Length; StreamWriter sw = new StreamWriter(request.GetRequestStream()); sw.Write(json); sw.Close(); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); StreamReader sr = new StreamReader(response.GetResponseStream()); string responseJson = sr.ReadToEnd(); sr.Close(); return responseJson; }  relying on the default/autodetect encoding from the Streamwriter. I will definitely stick with the first one that seems less error prone I wasn't using Encoding at first.modified 3 Dec '12 - 12:37. Sign In·View Thread·Permalink
 Re: Encoding of special characters Mehdi Gholam 7 Dec '12 - 5:47
 I have fixed this issue in v2.0.11. Its the man, not the machine - Chuck Yeager If at first you don't succeed... get a better publicist If the final destination is death, then we should enjoy every second of the journey. Sign In·View Thread·Permalink
 Good work Member 9548204 16 Nov '12 - 19:42
 Re: Good work Mehdi Gholam 20 Nov '12 - 4:47
 Thanks! Its the man, not the machine - Chuck Yeager If at first you don't succeed... get a better publicist If the final destination is death, then we should enjoy every second of the journey. Sign In·View Thread·Permalink
 My vote of 5 ravithejag 15 Nov '12 - 17:34
 IsDefined Suggestion Andrew Rissing 15 Nov '12 - 7:30
 When checking for the presence of attributes, you'll want to use IsDefined, rather than GetCustomAttributes.   MSDN[^]   It is about 4x times faster than using GetCustomAttributes. Sign In·View Thread·Permalink
 Re: IsDefined Suggestion Mehdi Gholam 15 Nov '12 - 7:36
 Thanks Andrew!   Although fastJSON only does this once per type but still anything that goes faster is good Its the man, not the machine - Chuck Yeager If at first you don't succeed... get a better publicist If the final destination is death, then we should enjoy every second of the journey. Sign In·View Thread·Permalink
 Re: IsDefined Suggestion Andrew Rissing 15 Nov '12 - 7:58
 More followup.... Andrew Rissing 15 Nov '12 - 7:58
 Take the following with a grain of salt, I'm looking over the code fairly quickly, so I might miss obvious things.   -SafeDictionary - Why have an internal class contain locks, especially on an instance level? I'd imagine that serializing/deserializing a string should not run into multi-threaded issues. Furthermore, you're breaking a standard expectation for .NET (static members are thread safe, while instance members are not). I think it would be safe enough to just use regular Dictionaries and rely on the user of your class to handle the locking properly. Otherwise, performance suffers for those not using in a multi-threaded way. -Formatter.AppendIndent - Since you're just appending four spaces, you might want to use StringBuilder.Append(char, int) and just multiply count by 4. It'd likely be faster. -JSON.ToObject - You have several calls to GetGenericTypeDefinition. You may want to cache that result off rather than calling it again and again. -JSON.CreateMyProp - You may want to look at this[^]. You could do an initial test to see if the type is Nullable, get the underlying type and then reduce the number of checks that you have (ex. type.GetGenericArguments()[0]). -myPropInfo - You spend time trying to find out what type something is. Why not instead of capturing that into a bool, capture a delegate to do something with it? It would reduce the amount of code you have and allow you to not pay the penalty of going over all the different types again. You could also use a factory pattern to create a concrete type (from an abstract base that defines the functionality) that handles it for the specific case. Either way would work. Sign In·View Thread·Permalink
 Re: More followup.... Sosum 16 Nov '12 - 23:07
 I guess: SafeDictionary has locks because it is used by the JsonRegistry which is static. Therefore, multiple threads can access the dictionary at runtime. Since the dictionary is created and populated on demand (new type to parse etc), it should be thread-safe.   I have tried to replace SafeDictionary with the ConcurrentDictionary but this decreases portability a lot. In fact I believe that the JsonRegistry should not be static. Changing parameters can too easily lead to unexpected output: 1. Set IncludeReadOnly= false, serialize 2. Set IncludeReadOnly= true, serialize=> fails, since it uses the cache which was populated based on the previous definition (1).   Aron Sign In·View Thread·Permalink
 Re: More followup.... Sosum 25 Nov '12 - 1:56
 Hi Andrew,   in my private version of FastJson I tried to implement your proposal in replacing the myPropInfo with a dictionary lookup. The outcome was devastating. The performance dropped about more than 200% in the given benchmark.   Interesting however is, that a combination if-else block (as-is) with a dictionary brings a significant bonus when exotic types are used.   You can check that version at: http://www.innotags.de/download/Apolyton.FastJSON.zip[^] Sign In·View Thread·Permalink
 Re: More followup.... Andrew Rissing 26 Nov '12 - 4:11
 Interesting.   I wasn't recommending a dictionary for that portion, but rather to capture an action to perform instead of a set of multiple flags to determine what to do later. Sign In·View Thread·Permalink
 Re: More followup.... Mehdi Gholam 26 Nov '12 - 4:37
 If any one can make fastJSON faster I am all ears Its the man, not the machine - Chuck Yeager If at first you don't succeed... get a better publicist If the final destination is death, then we should enjoy every second of the journey. Sign In·View Thread·Permalink
 Complex custom type Member 9595122 12 Nov '12 - 21:45
 Hi Mehdi,   nice work! I run though into a problem, when I tried to deserialize a JSON into a polymporphic objects. My object model is similar to city => list => list   Since I don't know what animals are within a zoo, I just have a type animal for each zoo. The problem is now, that only animals of type animal are created and not dogs, cats, etc.   Now, I would like to solve this problem through a custom type animal, in which I can check the supplied json for the necessary properties for each animal (dog barks, cat miaus, etc.)   The issue is now, that the current implementation (2.0.9) passes only a string to the custom deserializer and throws an error, if the custom type consist of multiple properties or additional object. I was now wondering if this could be changed to the passed parameter from string to a dictionary or full json object.   thanks for your feedback, Chris Sign In·View Thread·Permalink
 Re: Complex custom type Mehdi Gholam 13 Nov '12 - 3:03
 Thanks Chris!   "Custom Types" is intended for RECT, COLOR, ... etc. not for classes. fastJSON will automatically handle nested types for you if you have enabled the extensions (and given the dog inherits from animal). Its the man, not the machine - Chuck Yeager If at first you don't succeed... get a better publicist If the final destination is death, then we should enjoy every second of the journey. Sign In·View Thread·Permalink
 Re: Complex custom type Member 9595122 13 Nov '12 - 3:29
 hi Mehdi, thanks for the quick response. The Problem is that those nested types defined as follow in JSON:   A point: { "geometry" : { "x" : 2781859.5718259001, "y" : 5104563.3898882624 }   A polygon: { "geometry": { "rings": [ [ [123.445, 23.456], [33.123, 23.4345, [33.125, 23.4345, [123.2342, 23.4345] ], [ [123.445, 23.456], [33.123, 23.4345, [33.125, 23.4345, [123.2342, 23.4345] ] ] } }   (PS: I know, this is not best way to do this, but it was given to me as such and can not be changed )   I would need now to create a GeometryPoint and GeometryPolygon object, which belongs to a dataset which has a property Geometry (which can be point or polygon).   ==> Dataset.Geometry could be of type GeometryPoint or GeometryPolygon (and both inherite from the base type Geometry)   I believe, that for this purpose I would need a custom type with needs to be able to parse the appropriate JSON substrings, yet those substrings need to be passes as Dictionary. Therefore my question regarding the passed type.   Unless, there's another approache to this problem?   thanks for your help, Chris Sign In·View Thread·Permalink
 Re: Complex custom type Mehdi Gholam 13 Nov '12 - 4:02
 Ah! the data does not have the $type extensions... Try the Parse() method instead, it will give you a dictionary and list of object collections. Its the man, not the machine - Chuck Yeager If at first you don't succeed... get a better publicist If the final destination is death, then we should enjoy every second of the journey. Sign In·View Thread·Permalink  Code Review Sosum 9 Nov '12 - 0:45  Hi Mehdi, We are planning to use your work in our company. In that scope, I have done some major code review. For now, I can offer you two different packages, if you are interested: a small one and a big one. The first is primarily focusing on the public API applies primarily minor code review changes. This should definitely a value to the community. Performance characterisics should not have been changed. The second package is an intense review, in brief details: - Harmonizing with .NET naming conventions - Applying good principles like separation of concerns (with perf. in mind). - Improving exception reporting - Increasing flexibility of the framework: Property opt-in, Property opt-out. This should increase performance in real-life use cases. - Small performance drop 1-3% (custo types always available) - Unit test driven: all native serilization/ deserialization is tested (46+ Tests) - 5+ Bug fixes - Improved debugging capabilities In the near future, I will have to make the basic funcionality again available under Silverlight 5. Which critical feature was removed by Microsoft? Best Regards, Aron Sign In·View Thread·Permalink  Re: Code Review Mehdi Gholam 9 Nov '12 - 2:06  Thanks Aron! Anything which doesn't break usage is most welcome (I would like to change somethings but it would break running code for people). Post your changes to me or you can fork the code for yourself and publish that way. As for SL5, the code that doesn't exist is (in Reflection.cs): ... DynamicMethod dynamicSet = new DynamicMethod("_", typeof(object), arguments, type, true); ... I'm a bit put off by MS in this regard so I haven't put any time into creating a workaround for it. [as a side note fastJSON works as is in MonoDroid, and I will publish soon ] Its the man, not the machine - Chuck Yeager If at first you don't succeed... get a better publicist If the final destination is death, then we should enjoy every second of the journey. Sign In·View Thread·Permalink  Re: Code Review Sosum 16 Nov '12 - 22:59  Sorry Mehdi for the late response, but I am quite busy during the week. For now, I don't want to post a public alternative. Therefore, I have uploaded the packages to a different server. The first package was about code understanding and improving without changing or breaking stuff. http://www.innotags.de/download/fastJSON.zip[^] The second package is about bringing value to the code, improving and hardening it. Performance: =============================================== I have run additional performance tests on that package and I am not perfectly happy: - I lost 10% during serialization. Maybe you could have a quick look, if there is an obvious mistake. - Deserialization is equal, sometimes faster but not significally. Abstract from the readme.txt =============================================== The changes are basing on FastJSON 2.0.9 - All native non-exotic members are unit tested in serialization/ deserialization - 'Json' class is tested with the complex class used for unit testing. - NOT COVERED BY TESTS YET: - JsonParameter interpretations -$type support - I had to change the namespace to something in order to be able to compare with FastJson 2.0.9 - The benchmark console app has also been adjusted slightly.   NEW FEATURES =============================================== - Property Opt-in, Opt-out: See JsonParameter.SerializationPolicy. To be combined with DataMemberAttribute. I have choosen this attribute over Serializable attribute since the last is coming from System.Xml, DataMember from Runtime.Serialization. Performance hit first time the type is used. - Added support DataMember.Name which allows to declaratively abstract the json field name from the property name which increases robustness of the resulting json protocol. It will also easy the case-insensitive implementation a lot I think. Performance hit first time the type is used. - Added support for IgnoreDataMember. Useful for Opt-out scenarios. Performance hit first time the type is used. - Added support for encoding, see JsonParameters.Encoding. Performance hit depending on the encoding used (no hit, if default encoding is used).   FIXED ISSUES =============================================== - Benchmark: Using StopWatch instead of DateTime which is recommended to measure ellapsed time. - JsonSerializer: DateTime to Utc is now respecting the kind of the datetime (JsonSerializer_DateTimeUtc) - JsonSerializer: List of bytes was not properly serialized (see JsonSerializer_ByteEnumeration) - JsonPropertyInfo.CanWrite (formerly named MyPropInfo) was always false for fields (should be always true). - JsonPropertyInfo.Filled was never false. Returned by Reflection, which always sets it to true. Don't see the use of the variable. Removed. - JsonPropertyInfo.GenericTypes was always null except for dictionaries with the name "Dictionary".     PENDING ISSUES =============================================== - Benchmark mistake in BinaryFormatter: as you mention fastJSON based on streams is a lot slower. The BinaryFormatter consumes streams so it cannot directly be compared to FastJson. The use cases are different: in case of an http request for instance, the input value is 'stream' and not 'string'. In order to compare performance, the Json Benchmarks should also have the input value 'stream' and not string. The time to convert the input value have to be paid anyway -and it should be part of the FastJson Benchmark which is not the case. - JsonDeserializer deserialization of byte[] is still failing, see Json_ByteEnumerationClass - JsonRegistry is not threadsafe: changing ShowReadOnlyProperty has potential to corrupt running (de-)serializations. Should be removed. Unit tests reveal that the issue exists also in a single thread. - There is a bug in the $type extension. It has a risk of return the wrong type. One can see it when exotic benchmark is run which will report an InvalidCastException. Best Regards, Aron Sign In·View Thread·Permalink  ServiceStack.Text has a better support with ExpandoObject Alexandre Perez 7 Nov '12 - 7:09  dynamic employee = new ExpandoObject(); employee.Name = "John Smith"; employee.Age = 33; var manager = new ExpandoObject() as IDictionary; manager.Add("Name", "Allison Brown"); manager.Add("Age", 42); Console.WriteLine(((string)fastJSON.JSON.Instance.ToJSON(employee))); Console.WriteLine(fastJSON.JSON.Instance.ToJSON(manager)); Console.WriteLine(((string)ServiceStack.Text.JsonSerializer.SerializeToString(employee))); Console.WriteLine(ServiceStack.Text.JsonSerializer.SerializeToString(manager)); Output: {"$types":{"System.Dynamic.ExpandoObject, System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089":"1"},"$type":"1"} {"$types":{"System.Dynamic.ExpandoObject, System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089":"1"},"$type":"1"} ["[Name, John Smith]","[Age, 33]"] {"Name":"Allison Brown","Age":42} Sign In·View Thread·Permalink  Thanks Alexandre! I have had a couple of requests for "dynamic" support. PRO's: - a better coding experience - you don't need to create the containing class (less coding) CON's: - requires .net4+ - a bit slow Having said that I may add it as a better Parse() method for .net 4+ compilations. Its the man, not the machine - Chuck Yeager If at first you don't succeed... get a better publicist If the final destination is death, then we should enjoy every second of the journey. Sign In·View Thread·Permalink  Cannot detemine type error lobelt 2 Nov '12 - 1:12  I have a anoying problem. I am getting this error now. It has been working before in other projects but not in my recent. This is a test code that is thowing the error: Public Class fastJSONBuggTestC Public Settings As New SettingsC Public Class SettingsC Public Version As Integer = 1 Public RegistrationKey As String = "unknown" End Class Public Sub New() Dim testSettings As New SettingsC() Dim param As New fastJSON.JSONParameters() param.IgnoreCaseOnDeserialize = True param.SerializeNullValues = True param.UseExtensions = True param.UseFastGuid = True param.UseOptimizedDatasetSchema = True param.UseUTCDateTime = True param.UsingGlobalTypes = True Dim jsonString As String = fastJSON.JSON.Instance.ToJSON(Settings, param) Settings = fastJSON.JSON.Instance.ToObject(jsonString) End Sub End Class It is this row: Settings = fastJSON.JSON.Instance.ToObject(jsonString) that is throwing the error "Cannot determine type", anyone now why this is hapening now and not before? Thanks! Robin Andersson Sign In·View Thread·Permalink  Re: Cannot detemine type error Mehdi Gholam 7 Nov '12 - 20:45  Can you send me the JSON string generated? Its the man, not the machine - Chuck Yeager If at first you don't succeed... get a better publicist If the final destination is death, then we should enjoy every second of the journey. Sign In·View Thread·Permalink  My vote of 5 Devan_Monroe 24 Oct '12 - 6:33  Extremely through and highly optimized Sign In·View Thread·Permalink  Issues with Beautify() Timofey Vasenin 24 Oct '12 - 3:56  A couple of examples: One: ["foo0",{"foo1":"C:\\!bar1","foo2":"C:\\bar2"}] [ "foo0", { "foo1" : "C:\\!bar1", "foo2" : "C:\\bar2"}] Two: [{"foo":"'[0]"}] [ { "foo" : "'[ 0 ]"}] Sign In·View Thread·Permalink  Update of NuGet Package kct 24 Oct '12 - 0:45  Hi, great work and I'd really appreciate it if you try to update the NuGet package regularly. So everyone can update to the latest version easyly. Thanks a lot Sign In·View Thread·Permalink  Re: Update of NuGet Package Mehdi Gholam 24 Oct '12 - 4:31  I will try Its the man, not the machine - Chuck Yeager If at first you don't succeed... get a better publicist If the final destination is death, then we should enjoy every second of the journey. Sign In·View Thread·Permalink  Re: Update of NuGet Package kct 25 Oct '12 - 2:14  Thanks. 5-stars Sign In·View Thread·Permalink  Awesome work!!! but when will it can serialize anonymous type? xinsuiyuer 23 Oct '12 - 17:34  like: var arr2 = new[]{ new { Text = "M", Value = true}, new { Text = "F", Value = false } }; var ttt = fastJSON.JSON.Instance.ToJSON(arr2, new fastJSON.JSONParameters() { UseExtensions = false });  the result is : "[{},{}]" Sign In·View Thread·Permalink  Actually it will serialize but *not* deserialize anonymous types, just set the EnableAnonymousTypes = true parameter. Its the man, not the machine - Chuck Yeager If at first you don't succeed... get a better publicist If the final destination is death, then we should enjoy every second of the journey. Sign In·View Thread·Permalink  Deserialization of Dataset not working wolivier 22 Oct '12 - 4:47  Hello, I run the console test and it appears that deserialization of dataset is not working. Was it working in a previous version? Tkanks a lot. Sign In·View Thread·Permalink  Re: Deserialization of Dataset not working Mehdi Gholam 22 Oct '12 - 4:59  What error are you getting? Its the man, not the machine - Chuck Yeager If at first you don't succeed... get a better publicist If the final destination is death, then we should enjoy every second of the journey. Sign In·View Thread·Permalink  Re: Deserialization of Dataset not working wolivier 22 Oct '12 - 5:52  Thans for your answer. The error is "Cannot determine type" The code who provide error is: ds = CreateDataset(); string text = fastJSON.JSON.Instance.ToJSON(ds); DataSet ds2 = (DataSet)fastJSON.JSON.Instance.ToObject(text); If the dataset is a property of an object, it's working. But if the Dataset is the object it doens't work. Sign In·View Thread·Permalink  Re: Deserialization of Dataset not working Mehdi Gholam 22 Oct '12 - 6:24  Root level deserialize of a dataset is not supported at the moment. The code will work fine if the dataset was in an object. Its the man, not the machine - Chuck Yeager If at first you don't succeed... get a better publicist If the final destination is death, then we should enjoy every second of the journey. Sign In·View Thread·Permalink  Re: Deserialization of Dataset not working Mehdi Gholam 23 Oct '12 - 0:34  I have added root level DataSet and DataTable support and will post shortly. var ds = CreateDataset(); var s = fastJSON.JSON.Instance.ToJSON(ds); var o = fastJSON.JSON.Instance.ToObject(s); Its the man, not the machine - Chuck Yeager If at first you don't succeed... get a better publicist If the final destination is death, then we should enjoy every second of the journey. Sign In·View Thread·Permalink  fastJSON and json_encode() in PHP 5.3 for inner clas ___alex____ 17 Oct '12 - 9:50  For example i have code in c#: public class TestB { public int b = 3; public string c = "AA"; public TestB() { } }; public class TestA { public int a = 0; public TestB tb = new TestB(); public TestA() { } }; void method() { WebRequest webRequest = WebRequest.Create("http://localhost/"); webRequest.ContentType = "application/json"; webRequest.Method = "POST"; TestA ta = new TestA(); string a = JSON.Instance.ToJSON(ta); byte[] bytes = Encoding.UTF8.GetBytes(a); Stream os = null; // send the Post webRequest.ContentLength = bytes.Length; //Count bytes to send os = webRequest.GetRequestStream(); os.Write(bytes, 0, bytes.Length); //Send it if (os != null) { os.Close(); } WebResponse webResponse = webRequest.GetResponse(); StreamReader sr = new StreamReader(webResponse.GetResponseStream()); string s = sr.ReadToEnd(); TestB tb = JSON.Instance.ToObject(s); }  and i have a server in php v. 5.3 to response this: $data = file_get_contents("php://input"); $obj = json_decode($data); $ret = json_encode($obj->tb); $len = strlen($ret); header("Content-length: $len"); echo$ret;   return;    So in the class is return inner value of class TestB (tb). Send is ok, it sends $types, and$type. But in return it send me: {"$type":"2","b":3,"c":"AA"} Doesn't send information about types ($types), and in your code the value of globaltypes is empty because the return information is \$types and code will have exception on line: if (globaltypes.TryGetValue((string)tn, out tname)) tn = tname; Sign In·View Thread·Permalink
 ParseNumber bug on Double format ( ie. 0.123e-45 ) .µZ Hg. 12 Oct '12 - 6:59
 Hi, I have a exception while parsing a json string which contains numbers formatted as: Points": [   { "X": 0.1097, "Y": 0, "Z": 4.16366160299608e-18 // <- bug here } ] To fix it, in JSONParser.cs (line 308, function ParseNumber()) , replace: return decimal.Parse(s,NumberFormatInfo.InvariantInfo);   with: return Double.Parse(s,NumberFormatInfo.InvariantInfo);   Thanks.   Alex. Sign In·View Thread·Permalink
 Re: ParseNumber bug on Double format ( ie. 0.123e-45 ) Mehdi Gholam 12 Oct '12 - 8:31
 Unfortunately the GermanNumbers test fails with this.   I will try to find a work around. Its the man, not the machine - Chuck Yeager If at first you don't succeed... get a better publicist If the final destination is death, then we should enjoy every second of the journey. Sign In·View Thread·Permalink
 Re: ParseNumber bug on Double format ( ie. 0.123e-45 ) Mehdi Gholam 13 Oct '12 - 6:52
 Fixed now in v2.0.8. Its the man, not the machine - Chuck Yeager If at first you don't succeed... get a better publicist If the final destination is death, then we should enjoy every second of the journey. Sign In·View Thread·Permalink
 Re: ParseNumber bug on Double format ( ie. 0.123e-45 ) .µZ Hg. 14 Oct '12 - 21:22
 Thanks Andrew!   The following works fine:  public class arrayclass { public int[] ints { get; set; } public string[] strs; } [Test] public static void ArrayTest() { arrayclass a = new arrayclass(); a.ints = new int[] { 3, 1, 4 }; a.strs = new string[] {"a","b","c"}; var s = fastJSON.JSON.Instance.ToJSON(a); var o = fastJSON.JSON.Instance.ToObject(s); } I have added it to the unit tests. Its the man, not the machine - Chuck Yeager If at first you don't succeed... get a better publicist If the final destination is death, then we should enjoy every second of the journey. Sign In·View Thread·Permalink