Click here to Skip to main content
Click here to Skip to main content

fastJSON

By , 24 May 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>();
zoo1.animals.Add(new cat());
zoo1.animals.Add(new dog());

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 
  • Thread safe   
  • 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 it
  • Pretty compact output
  • Version unfriendly : must be deserialized into the exact class that was serialized
  • Not good for storing of data because of the versioning problem
  • Not human readable
  • Not 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 datasets
  • First implementation I saw which could handle polymorphic object collections
  • Large dll size ~320kb
  • Slow in comparison to the rest in the list
  • Source 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 follow
  • Requires .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 serializer
  • Pretty small dll size ~91kb  
  • Can't handle polymorphic object collections
  • Requires at least .NET 3.5
  • Fails on Nullable types
  • Fails 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. 

Additions in v1.7.5

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

Additions v1.7.6

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

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

Additions v1.8

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 = @"
        AJKLjaskljLA
   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/exotic.png

  • 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

fastJSON/v1.4.png

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

fastJSON/v1.5.png

  • 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

fastJSON/v1.6.png

  • 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

fastJSON/v1.7.png

  • 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 :
    • added microsoft json evaluation
    • added consoletest project to downloads for testing newer exotic types
    • 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
    • safedictionary check before add
    • 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
    • ShowReadOnlyProperties added for exporting readonly properties (default = false)
    • 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
    • added unit tests
    • 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
    • added more tests
    • 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>(...) ) 
    • added dataset tests
  • Update v2.0.10 : 15th November 2012  
    • added MonoDroid project  
  • 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
         - using switch instead of linked if statements
         - parsing DateTime optimized
         - StringBuilder using single char output instead of strings for \" chars etc
  • Update v2.0.15 : 24th May 2013 
    • removed CUSTOMTYPE directives from code
    • fix for writing enumerable object

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Mehdi Gholam
Architect
United Kingdom United Kingdom
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)

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionAre there any plans to support deserialization of arrays?memberskalkin11-Oct-12 11:02 
First of all, thanks for sharing that little useful library! I just wonder why doesn't it support deserialization of arrays (admittedly, you can use List, but still)? The necessary code changes seem to be trivial.
 
Regards,
Andrew
AnswerRe: Are there any plans to support deserialization of arrays?mvpMehdi Gholam11-Oct-12 17:06 
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.

GeneralRe: Are there any plans to support deserialization of arrays?memberskalkin12-Oct-12 5:29 
Thanks a lot!
Generalgood articlememberpoint645-Oct-12 3:00 
Thumbs Up | :thumbsup: Good tips
QuestionDeserializing Immutable ClassesmemberIker eL_FRuTeRo5-Oct-12 1:53 
¿It is possible to deserialize immutable classes?
If i have a class like this:
class Immutable
{  
    public Immutable( long id )
    {
        this.Id = id;
    }
    public long Id { get; private set; }
}
with JsonNet i must add a attribute to them and an empty constructor and leave the class like this:
class Immutable
{
    [JsonConstructor]
    private Immutable() : this(0) { }
 
    public Immutable( long id )
    {
        this.Id = id;
    }
    [JsonProperty]
    public long Id { get; private set; }
}
Thanks
Iker eL_FRuTeRo

AnswerRe: Deserializing Immutable ClassesmvpMehdi Gholam5-Oct-12 3:28 
You don't need any attributes with fastJSON, but a default constructor is required.
 
You can get the json output for readonly properties by setting the ShowReadOnlyProperties = true in JSONParameters.
 
Obviously when deserializing the readonly properties will be ignored and not set.
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.

GeneralRe: Deserializing Immutable ClassesmemberIker eL_FRuTeRo7-Oct-12 21:03 
In a immutable object, all its properties are readonly as they are immutable.
can i deserialie them without adding a public setter?
Thank you very much
Iker eL_FRuTeRo

GeneralRe: Deserializing Immutable ClassesmvpMehdi Gholam7-Oct-12 21:14 
Unfortunately not since the deserializer is using the Set method defined on the class and if it is private then it will fail.
 
Obviously the designer of the class made the decision to make properties private, so it is unsafe to assume anything about the internal structure of the class when reflecting at the level of fastJSON.
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.

QuestionDeserializing System.Type Objectmemberlatentlone27-Sep-12 9:49 
I am trying to serialize and deserialize a variable of type System.Type. Is that possible? If yes, what am I doing wrong?
 
System.Type type = typeof(string);
var jsonText = JSON.Instance.ToJSON(type);
var newType = JSON.Instance.ToObject(jsonText) as Type;
 
I get the following exception:
 
System.Exception : Failed to fast create instance for type 'System.RuntimeType' from assemebly 'System.RuntimeType, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'
----> System.ArgumentNullException : Value cannot be null.
Parameter name: con
 
at fastJSON.JSON.FastCreateInstance(Type objtype) in JSON.cs: line 164
at fastJSON.JSON.ParseDictionary(Dictionary`2 d, Dictionary`2 globaltypes, Type type) in JSON.cs: line 471
at fastJSON.JSON.ToObject(String json, Type type) in JSON.cs: line 82
at fastJSON.JSON.ToObject(String json) in JSON.cs: line 75
 
(I also posted this on CodePlex: [^]. I am not sure where the official forum is.)
AnswerRe: Deserializing System.Type ObjectmvpMehdi Gholam27-Sep-12 10:17 
Serializers are generally meant to process "data" types not "meta" types, so unfortunately you can't work with Type as an input.
 
I prefer this forum than Codeplex as provides a better interface and is easier to work with.
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.

QuestionNewtonsoft.Json.JsonConvert format from fastJSONmemberosstekz26-Sep-12 17:48 
Trying to convert several legacy MVC3 apps to use fastJSON serializer to replace heavy Newtonsoft.Json.JsonConvert.SerializeXmlNode on XMLdocument or Datasets. Our client JavaScript apps require the Ex1 format below for use in jqGrid library. Tried w/ fastJSON (Ex4 & Ex5 output) but can not seem to get the key:value format like Ex1. Is Ex1 serialized output format possible in fastJSON? How? Many thanks for your help!
 
---------------------------------------------------------------------------
Ex1:Newtonsoft.Json.JsonConvert.SerializeXmlNode
{"person":[{"@id":"1","name":"Alan","url":"http://www.google.com"},{"@id":"2","name":"Louis","url":"http://www.yahoo.com"}]}
---------------------------------------------------------------------------
Ex2:JavaScriptSerializer.Serialize(xmlDoc.InnerXml)
"\u003croot\u003e\u003cperson id=\"1\"\u003e\u003cname\u003eAlan\u003c/name\u003e\u003curl\u003ehttp://www.google.com\u003c/url\u003e\u003c/person\u003e\u003cperson id=\"2\"\u003e\u003cname\u003eLouis\u003c/name\u003e\u003curl\u003ehttp://www.yahoo.com\u003c/url\u003e\u003c/person\u003e\u003c/root\u003e"
---------------------------------------------------------------------------
Ex3:JavaScriptSerializer: DataSetToJSON using dictionary
{"person":[["Alan","http://www.google.com","1"],["Louis","http://www.yahoo.com","2"],null]}
---------------------------------------------------------------------------
Ex4:fastJSON: DataSet to dictionary
{"person":[["Alan","http://www.google.com","1"],["Louis","http://www.yahoo.com","2"],null]}
---------------------------------------------------------------------------
Ex5:fastJSON.JSON.Instance.ToJSON(ds)
{"$schema":{"$type":"fastJSON.DatasetSchema, fastJSON, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null","Info":["person","name","System.String","person","url","System.String","person","id","System.String"],"Name":"root"},"person":[["Alan","http://www.google.com","1"],["Louis","http://www.yahoo.com","2"]]}
---------------------------------------------------------------------------
AnswerRe: Newtonsoft.Json.JsonConvert format from fastJSONmvpMehdi Gholam26-Sep-12 19:13 
As far as I can see you need
{"property": [ {row in object style key:value with a @id row counter}, {next row} ] }
Which outputs the column names also, while fastJSON outputs in the following style to save space:
{"property": [ [row data only], [next row] ] }
Currently fastJSON does not do this, however you can write your own custom serializer delegate for the property type your need.
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.

SuggestionLittle suggestion - RegisterCustomType<T> [modified]memberilmagotida18-Sep-12 6:18 
Hi,
what do you think about to add generic overload(s) of RegisterCustomType method?
 
something like your overload
public T ToObject<T>(string json)
for
public object ToObject(string json)
I suggest
public void RegisterCustomType<T>(Func<T, string> serializer, Func<string, T> deserializer)
{
    RegisterCustomType(typeof(T), (o) => serializer((T)o), (s) => deserializer(s));
}
and/or or (implements both overloads is not a good idea, this cause an ambiguous call when you call method using Lambda Expression)
public void RegisterCustomType<T>(Serialize<T> serializer, Deserialize<T> deserializer)
{
    RegisterCustomType(typeof(T), (o) => serializer((T)o), (s) => deserializer(s));
}
adding delegate fields
public delegate string Serialize<T>(T data);
public delegate T Deserialize<T>(string data);
Thank you for sharing your great job
Francesco

modified 19-Sep-12 5:01am.

GeneralRe: Little suggestion - RegisterCustomTypemvpMehdi Gholam18-Sep-12 7:05 
Nice, Francesco!
 
Will do in the next release 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.

GeneralRe: Little suggestion - RegisterCustomTypememberilmagotida18-Sep-12 8:26 
Thank you!
GeneralMy vote of 5memberilmagotida17-Sep-12 6:46 
Just great!
QuestionThread safetymemberPhilip Jander17-Sep-12 4:30 
Hi Mehdi,
 
under features you list fastJson as being threadsafe. I wonder if the _usingglobals field doesn't break this.
Unless you specify either true or false globally and never change it
through the Parameters, you can end up with the following scenario:
 
E.g. _usingglobals is set to false per Parameters.
Deserializing a json string which was serialized with global types and extensions will set it to true in ParseDictionary.
Intermittent serialization on another thread sets it back to false.
Ths initial Deserialization hits the "if (found)" on a sub-object (or even on the initial object after a thread yield), tn contains a number (e.g. "2") but _usingglobals is false again.
Therefore it will *not* look up the globaltypes but instead ultimately call Type.GetType("2") which must fail.
 
Cheers
Phil
AnswerRe: Thread safetymvpMehdi Gholam17-Sep-12 5:35 
Global type processing is handled in a class which is created per serialize/deserialize call, so it will not conflict.
 
Anyway it is being used aggressivly in RaptorDB which is testing it to it's metal.
 
If you do find any problem in the field let me know and I will fix it.
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.

GeneralRe: Thread safetymemberPhilip Jander17-Sep-12 22:37 
Here is a test showing the bug with version 2.0.5:
https://gist.github.com/3742035[^]
 
And here is a patch temporarily fixing the bug by using separate JSON instances for separate threads.
Disclaimer: I didn't check what it does to your timing.
https://gist.github.com/3742046[^]
 
Cheers,
Phil
GeneralRe: Thread safetymvpMehdi Gholam18-Sep-12 5:48 
This is intriguing...
 
I used the MS singelton pattern, I will change the code and see how it performs.
 
Thanks Phil!
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.

GeneralRe: Thread safetymemberPhilip Jander18-Sep-12 10:11 
Just to be sure: if you use the same kind of fix, you will need to make Parameters static + threadsafe, too. If you like, you can have a look at my fastJson fork on github. I essentially introduced a new static GlobalParameters and changed the Parameters to be an instance property accessing the new static one, for backwards compatbility.
 
It's funny that this went unnoticed (since 2.0.0 I guess). Probably the combination of sometimes using extensions and sometimes not is not too common.
 
Anyway, thank you for a really great library Smile | :)
GeneralRe: Thread safetymvpMehdi Gholam18-Sep-12 10:17 
Your right, it has always bugged me, but most people (me included) just use the defaults all the way and don't change mid execution.
 
ThreadStatic is very cool as I looked it up, learned something today, 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.

GeneralRe: Thread safetymemberJAMontgom9-Jan-13 11:51 
Mehdi,
 
I found this discussion because occasionally I am getting an error when using fastJSON (2.0.12) in a WPF app, which uses separate threads to update the UI. It is getting a null ref exception on globaltypes.TryGetValue in the following code block of ParseDictionary because globaltypes is null:
if (_usingglobals)
{
    object tname = "";
    if (globaltypes.TryGetValue((string)tn, out tname))
    tn = tname;
}
The state of globaltypes and _usingglobals are out of sync, which seems to be the issue discussed in this thread. I'm just guessing that _usingglobals is getting set to true somewhere else incorrectly.
 
I notice that elsewhere in this thread, Philip Jander made the statement "if you use the same kind of fix, you will need to make Parameters static + threadsafe, too", but this does not appear to have been implemented in version 2.0.6 along with the other threading fixes. _usingglobals is part of Parameters. Do you think this might be the cause of this issue?
 
Thanks,
 
Jeff Montgomery
GeneralRe: Thread safetymvpMehdi Gholam9-Jan-13 19:38 
Thanks Jeff!
 
This seems to be an edge case, I will try to track it down it would help if you can give me a test case where this happens for you.
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.

GeneralRe: Thread safetymemberPhilip Jander17-Sep-12 22:45 
As a sidenote (unrelated), the JSON generated for "ConcurrencyClassB" in the test has an extra comma. It doesn't seem to hurt, but I guess it shouldn't be there:
 
{,"PayloadB":{}}
GeneralRe: Thread safetymvpMehdi Gholam18-Sep-12 5:57 
Thanks I will check this, probably an edge case in the before after stringbuilders.
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.

GeneralRe: Extra comma (was: Thread safety)memberPhilip Jander18-Sep-12 10:14 
From a fast look, it seems that the culprit is
 
if (i == 0) // last non null
   _output.Append(",");
 
in JsonSerializer.
 
I let this comma pass, only if g.Count was > 1 in the first place *or* $type was written. It seems that this fixes the problem.
 

Cheers
Phil
GeneralRe: Extra comma (was: Thread safety)mvpMehdi Gholam9-Jan-13 19:39 
Commas should *finally* be fixed in v2.0.13.
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.

QuestionEdit a JSON filememberMember 878398916-Sep-12 22:29 
Hi @ all,
 
i'm a beginner in C# but i have good knowledge of PHP & Phyton.
I have a Program which opens a JSON encoded file and modifies it with File.Append() but i want to edit the JSON as an Array (or something similar), so i can search specific keys and edit the values.
 
i can load the file:
 
object jsonText;
file_path = "path_to_file"
 
jsonText = fastJSON.JsonParser.JsonDecode(File.ReadAllText(file_path));
How can i loop through the key0>values or edit specific values ?
AnswerRe: Edit a JSON filemvpMehdi Gholam16-Sep-12 23:10 
Use Parse() it will give you dictionaries and lists.
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.

GeneralRe: Edit a JSON file [modified]memberMember 878398916-Sep-12 23:38 
Thank you very much for your help!
 
My Code Now:
object jsonText;
temp = File.ReadAllText(path);
jsonText = fastJSON.JSON.Instance.Parse(temp);
 
i get the JSON in jsonText but i find no way to loop through the array or to modify explicit key=>value pairs :/
 
Can you give me a helping line what i do wrong?

modified 17-Sep-12 8:02am.

GeneralRe: Edit a JSON filememberPalladion17-Sep-12 22:51 
Sorry can you help me? i don't get it.
 
if i use this, i get the Object but i cant loop through it:
object jsonText;
jsonText = fastJSON.JSON.Instance.Parse(temp);
 
if i cast it as a Dictonary, jsonText is NULL:
Dictionary<string, string> jsonText;
jsonText = fastJSON.JSON.Instance.Parse(temp) as Dictionary<string, string>;

GeneralRe: Edit a JSON filemvpMehdi Gholam18-Sep-12 5:44 
It should be Dictionary<string,object> if the original object was a class otherwise it could be List<object> if it was an array.
 
Any way use
var o = fastJSON.JSON.Instance.Parse(temp);
and run in the debugger and you will see the structure if you watch the o variable.
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.

QuestionRecursive serialization? [modified]memberi007-Sep-12 14:46 
Looks good ... I don't have VS2010 ... but out of curiosity can it handle the following case:
 
Class Animal
-> Zoo BelongsToZoo
-> String AnimalName
 
Class Zoo
-> String ZooName
-> list Animals
 
In the above case if we have an animal with the zoo set to something, and the zoo object contains the same animal in its list xml serialization will not work, does yours?
 
Kris


modified 8-Sep-12 2:01am.

AnswerRe: Recursive serialization?mvpMehdi Gholam7-Sep-12 19:26 
Yes and no, there is a 10 [configurable] levels deep limit that the serializer will go down a nested recursive hierarchy before breaking out of the loop.
 
Flat "text" serialize formats like XML and JSON are not meant to be used with graph memory structures.
 
It is possible to create a structure of list of objects and graph which use pointers to the object list which could work (much like how $types are handled).
 
Interesting concept...
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.

GeneralRe: Recursive serialization? [modified]memberi007-Sep-12 19:49 
Hrm... so your serializer would serialize each level of the same animal as a separate object?
 
In that case... when the object gets originally created:
 
giraffe.BelongsToZoo.animals.contains(giraffe)
 
would equal true...
but when serialized and deserialized this would not be the case as the giraffe in the zoo would be a different object.
 
The binary serializer does not have this issue.
 
Kris


modified 8-Sep-12 2:01am.

GeneralRe: Recursive serialization?mvpMehdi Gholam7-Sep-12 19:54 
Yes that is the case, like I said "text" serializers have this problem.
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.

GeneralRe: Recursive serialization?memberi007-Sep-12 20:10 
Couldn't a text serializer go ...
 
Each time you serialize an object add it to a list
 
if the object that we are serializing has already been serialised (in the list) then add a pointer to the location that it was serialized instead of trying to re-serialize it.
 
... then it should then be able to correctly text serialize cyclic objects?
 
Also it isn't a limitation of text serializers ... some work with cyclic objects using the method that i discussed above
 
Kris

GeneralRe: Recursive serialization?mvpMehdi Gholam7-Sep-12 20:13 
I did say this in my original answer. Smile | :)
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.

GeneralRe: Recursive serialization?memberi007-Sep-12 20:15 
whops :P didn't see that
 
... out of curiosity why is it limited to 10 levels deep?
 
Kris

GeneralRe: Recursive serialization?mvpMehdi Gholam7-Sep-12 20:31 
10 is arbitrary, the limit is so you don't go in an endless loop.
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.

GeneralRe: Recursive serialization?memberbitterskittles24-Oct-12 1:55 
iirc, DataContractSerializer can preserve object references.
I'd also like to see benchmark results for DataContractSerializer too Smile | :)
 
http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractserializer.preserveobjectreferences.aspx[^]
http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractattribute.isreference.aspx[^]
QuestionSerialize Nullmembersoftwarejaeger5-Sep-12 4:05 
Hello Mr Gholam,
 
at first... i'm using fastJSON a lot and it is now my standard for serializing/deserializing and storing any sort of data. It is so great, thanks for all that great work!
 
Now to the (little) problem. If i have a object, which is null (see code below) and want to serialize that, i get an exception.
This is for many people okay, but wouldn't it be better, just to check if the object is null and then to return "null"? Because in my application, it is allowed, that for example that property is null. But that would crash my serialization.
 
Dictionary<string,string> myDict = null;
fastJSON.JSON.Instance.ToJSON(myDict); //<-- Object reference not set to an instance of object
 
Maybe we could do this with a new JSONParameter?
Is there any way to get this as "standard" in your project? I wouldn't like now to create my own branch, just for this simple piece of code, which would improve a lot of scenarios for all developers out there.
 
Thank you!
AnswerRe: Serialize NullmvpMehdi Gholam5-Sep-12 5:30 
You would expect "null" as an output (without the quotes).
 
I will fix this in the next release 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.

GeneralRe: Serialize Nullmembersoftwarejaeger5-Sep-12 20:13 
This would be great. Thank you very much.
Bug_before bugmemberqio945-Sep-12 0:47 
        JSONParameters JSONP = new JSONParameters();
        JSONP.UseExtensions = false;    // enable disable the $type and $map inn the output
        JSONP.SerializeNullValues = false;
        JSONP.ShowReadOnlyProperties = true;
        Response.ContentType = "text/plain";
        Response.Write(JSON.Instance.ToJSON(new testcl(), JSONP));
        class testcl{
            public int cardType;
            public bool groupStatus;
            public string groupQBId;
        }
 
"cardType":0,"groupStatus":false}
 
fix:
internal string ConvertToJSON(object obj)
{
    WriteValue(obj);
 
    string str = "";
    if (_params.UsingGlobalTypes && _globalTypes != null && _globalTypes.Count > 0)
    {
        StringBuilder sb = _before;
        sb.Append("\"$types\":{");
        bool pendingSeparator = false;
        foreach (var kv in _globalTypes)
        {
            if (pendingSeparator) sb.Append(',');
            pendingSeparator = true;
            sb.Append("\"");
            sb.Append(kv.Key);
            sb.Append("\":\"");
            sb.Append(kv.Value);
            sb.Append("\"");
        }
        sb.Append("},");
        sb.Append(_output.ToString());
        str = sb.ToString();
    }
    else
        str = _before.ToString() + _output.ToString();
 
    return str;
}

GeneralRe: _before bugmemberdonat.hutter5-Sep-12 3:50 
the error occurs under the condition:
a) UseExtensions = false
b) UsingGlobalTypes = true (which is default)
and (_globalTypes.Count == 0)
 
therefore fix it this way (see writeObject, where _before is created, and _output is cleared:
if (_params.UsingGlobalTypes)
{
    StringBuilder sb = _before; // see writeObject
    if (_globalTypes != null && _globalTypes.Count > 0)
    {
        sb.Append("\"$types\":{");
...
    }
    sb.Append(_output.ToString());
    str = sb.ToString();
}
else
    str = _output.ToString();
return str;

GeneralRe: _before bugmvpMehdi Gholam5-Sep-12 5:35 
Thanks, I will add the code in the next release 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.

BugSerializeNullValues bugmemberqio944-Sep-12 22:46 
bug ex:
      {
         "cardType":"CUSTOMCODE",
         "groupStatus":false,
      },
 
fix code:
foreach (var p in g)
{
    object o = p.Getter(obj);
    if ((o == null || o is DBNull) && _params.SerializeNullValues == false)
        //append = false;
        continue;
    else
    {
        if (append)
            _output.Append(',');
        WritePair(p.Name, o);
        if (o != null && _params.UseExtensions)
        {
            Type tt = o.GetType();
            if (tt == typeof(System.Object))
                map.Add(p.Name, tt.ToString());
        }
        append = true;
    }
}

GeneralRe: SerializeNullValues bugmvpMehdi Gholam4-Sep-12 23:59 
Please send me the code that generated this (the object you were serializing).
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.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130617.1 | Last Updated 24 May 2013
Article Copyright 2011 by Mehdi Gholam
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid