|
|
Comments and Discussions
|
|
 |

|
There is an implicit assumption that the same assembly will both serialize and deserialize the JSON object.
However, where this is not the case, the "$type..." syntax will fail.
Unfortunately, using the assembly name once in the lib, the assembly is different.
I am not unsure if my change are the neatest, but I modified the code in;
a) JsonSerializer.cs not use the serializer assembly name in WriteObject();
private void WriteObject(object obj)
{
Indent('{');
Dictionary<string, string> map = new Dictionary<string, string>();
Type t = obj.GetType();
bool append = false;
if (useExtension)
{
#if gtrm
WritePairFast("$type", JSON.Instance.GetTypeAssemblyName(t));
#else
WritePairFast("$type", t.FullName);
#endif
append = true;
}
and b)in JSON.cs to use the callers Assembly name in ToObject();
public T ToObject<T>(string json)
{
return (T)ToObject(json, typeof(T), typeof(T).Assembly);
}
public object ToObject(string json)
{
return ToObject(json, null, null);
}
public object ToObject(string json, Type type)
{
Dictionary<string, object> ht = new JsonParser(json).Decode() as Dictionary<string, object>;
if (ht == null) return null;
return ParseDictionary(ht, type, null);
}
public object ToObject(string json, Type type, Assembly asm)
{
Dictionary<string, object> ht = new JsonParser(json).Decode() as Dictionary<string, object>;
if (ht == null) return null;
return ParseDictionary(ht, type, asm);
}
private object ParseDictionary(Dictionary<string, object> d, Type type)
{
return ParseDictionary(d, type, null);
}
private object ParseDictionary(Dictionary<string, object> d, Type type, Assembly asm)
{
object tn = "";
bool found = d.TryGetValue("$type", out tn);
#if !SILVERLIGHT
if (found == false && type == typeof(System.Object))
{
return CreateDataset(d);
}
#endif
if (found && asm != null)
type = GetTypeFromCache((string)tn + ", " + asm.FullName);
|
|
|
|

|
I noticed that properties of a particular c# object get ignored upon serialization if they do not have both 'get' and 'set'. Is this intended behavior? I would much like to not have to add 'set' to every property which I've defined to only contain an accessor.
|
|
|
|

|
Hi Mehdi
Great job, this is a very useful library.
I am trying to deserialize a DataTable already serialized with fastJSON but with no success, the deserilized DataTable is always empty.
I am using something like this:
DataTable DataTableToDeserialize = fastJSON.JSON.Instance.ToObject<DataTable >(jsonText)
I am sure I am missing something but I cannot figure out what (I am newbie in serialization game). Can you please provide an example how can I do this?
Thanks in advance
|
|
|
|

|
Does fast JSON handle dates in format:
"born":"\/Date(1314195549619+0100)\/",
like those produced by System.Runtime.Serialization.Json.DataContractJsonSerializer
or only in format yyyy-MM-dd HH:mm:ss ?
|
|
|
|

|
Hi,
i have a minor problem with this jsonString:
string jsonstring = "{\"id\":\"0x3\",\"schedule\":[{\"DateBegin\":\"18\",\"DateEnd\":\"19\"},{\"DateBegin\":\"26\",\"DateEnd\":\"26\"}]}"
and my custom types
public class MyType(){
public string id{get;set;}
public MySchedule[] schedule{get;set;}
}
public class MySchedule(){
public string dateBegin{get;set;}
public string dateEnd{get;set;}
}
MyType obj = fastJSON.JSON.Instance.ToObject<MyType>(jsonstring);
FastJson does a good job on setting the id. Any suggestions how to get it working for MySchedule? Currently dateBegin and dateEnd are null.
|
|
|
|

|
Hi
I cannot take a json string and convert it to a collection of objects.
I thought it could handle this but maybe I am doing it wrong or misunderstood.
> Handles polymorphic collections of objects
Here is an example I did in a C# cmd line app(just download the cs files and add to a project and copy the follow code to test).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
List<Class1> store = new List<Class1>();
for (int i = 0; i < 3; i++)
{
Class1 c = new Class1();
c.Name = "test";
c.Start = DateTime.Now;
store.Add(c);
}
string jsonResult = fastJSON.JSON.Instance.ToJSON(store);
List<Class1> backToObject = fastJSON.JSON.Instance.ToObject<List<Class1>>(jsonResult);
}
}
public class Class1
{
public string Name { get; set; }
public DateTime Start { get; set; }
}
}
backToObject is always null.
|
|
|
|

|
public class T { public bool B{get;set;} }
json: {"B":"True"}
fixed:
JSON.cs
add method:
private bool CreateBool(string s)
{
bool r;
if (!bool.TryParse(s, out r))
{
r = false;
}
return r;
}
About 482 line:
else if (pi.isBool)
oset = (bool)v;
->
else if (pi.isBool)
oset = CreateBool(v.ToString());
|
|
|
|

|
private DateTime CreateDateTime(string value)
{
int year = (int)CreateLong(value.Substring(0, 4));
int month = (int)CreateLong(value.Substring(5, 2));
int day = (int)CreateLong(value.Substring(8, 2));
int hour = (int)CreateLong(value.Substring(11, 2));
int min = (int)CreateLong(value.Substring(14, 2));
int sec = (int)CreateLong(value.Substring(17, 2));
if (UseUTCDateTime == false)
return new DateTime(year, month, day, hour, min, sec);
else
return new DateTime(year, month, day, hour, min, sec, DateTimeKind.Utc).ToLocalTime();
}
value="2010-08-05" will be failed.
Fixed:
private DateTime CreateDateTime(string value)
{
if (!string.IsNullOrEmpty(value) && value.Length == 19)
{
int year = (int)CreateLong(value.Substring(0, 4));
int month = (int)CreateLong(value.Substring(5, 2));
int day = (int)CreateLong(value.Substring(8, 2));
int hour = (int)CreateLong(value.Substring(11, 2));
int min = (int)CreateLong(value.Substring(14, 2));
int sec = (int)CreateLong(value.Substring(17, 2));
if (UseUTCDateTime == false)
return new DateTime(year, month, day, hour, min, sec);
else
return new DateTime(year, month, day, hour, min, sec, DateTimeKind.Utc).ToLocalTime();return new DateTime(year, month, day, hour, min, sec);
}
else
{
DateTime returnX;
if (DateTime.TryParse(value, out returnX))
{
return returnX;
}
else
{
return new DateTime();
}
}
}
|
|
|
|

|
hi
i had got a exception while parse a complex model that include a dictionary property
Model:
public class Cfg_Device
{
public string device { get; set; }
public Dictionary<string, object> config { get; set; }
}
public class Cfg_DeviceCollection
{
public Cfg_Device CAN_confort { get; set; }
public Cfg_Device CAN_is { get; set; }
public Cfg_Device CAM_rear { get; set; }
}
public class Cfg_Root
{
public Cfg_DeviceCollection device { get; set; }
}
json:
{
"device":{
"CAN_confort" : {"device":"TTLCAN", "config":{"com":"COM19"}},
"CAN_is" : {"device":"","config":{}},
"CAM_rear" : null,
"CAM_right" : null,
"CAM_left" : null,
"CAM_front" : null
}
}
Exception: json.cs line 512
source code:
...
else if (pi.isDictionary || pi.isHashtable)
{
oset = CreateDictionary((ArrayList)v, pi.pt, pi.GenericTypes);
}
my suggestion:
else if (pi.isDictionary || pi.isHashtable)
{
if (v is IDictionary) oset = v;
else
oset = CreateDictionary((ArrayList)v, pi.pt, pi.GenericTypes);
}
|
|
|
|

|
sample code:
1,====================================================================
KeyValuePair kv = new KeyValuePair(1, "123");
string f = fastJSON.JSON.Instance.ToJSON(kv);
2,===============.NET 3.5 or 4.0======================================
object o = new { Cycle = new { ID = 1, Name = "2" }, DDD = new { Age = 33, Sex = true } };
string f = fastJSON.JSON.Instance.ToJSON(o);
SORRY, MY ENGLISH IS VERY POOR!!!
|
|
|
|

|
i tried to using fastJson but it occured a error in ToObject(). i'm using VS2010 with .NET framework 4. i downloaded fastjson 1.9.2, and build it, and refrence dll into my project, and do follow codes: <pre>using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { class JsonTest { private string a; private string b; public string A { get { return a; } set { a = value; } } public string B { get { return b; } set { b = value; } } } class Program { static void Main(string[] args) { JsonTest k = new JsonTest(); string jsonText = fastJSON.JSON.Instance.ToJSON(k); Console.Write(jsonText); JsonTest l = new JsonTest(); //the error occured here. l = fastJSON.JSON.Instance.ToObject<JsonTest>(jsonText); } } } </pre>
the exception throwed by fastJson, and full message is following:
Failed to fast create instance for type 'ConsoleApplication1.JsonTest' from assemebly 'ConsoleApplication1.JsonTest, ConsoleApplication1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'
|
|
|
|

|
Hello,
I am looking for a JSON/C# parser which allows me to mix access between a streaming style API and one that does object binding.
Pls let me explain by example (from my Java code based on Jackson).
Client API:
public void call(String procedureId, Class<?> resultType, OnCallResult resultHandler, Object... arguments);
* Wire format for calls.
*
* Call (client-to-server JSON message):
*
* ["call", <callId>, <procedureId>, <argument>]
*
* Result (server-to-client JSON message):
*
* ["callresult", <callId>, <result>]
The argument is marshalled automatically via object inspection (done by Jackson), the result is deserialized into resultType.
The challange with receiving is: I need to first deser. "callresult" and callId, then lookup the desired resultType in a map indexed by callId, and then use object-binding based deser. to unser. the result.
Thus, I need both: low-level and data-binding high-level in one parser framework.
Is that possible with fastJSON? How?
If not, do you know a lib. that allows this?
Thanks alot,
Tobias
|
|
|
|

|
See code below. The "FooTest" function is a simple test to confirm that object f can be converted to json and back again.
When using an enum as a Dictionary key, there appears to be a bug preventing the enum-as-string from converting back to the enum.
The runtime exception is
System.InvalidCastException : Invalid cast from 'System.String' to 'MyProject.unit.test.Numero'.
at System.Convert.DefaultToType(IConvertible value, Type targetType, IFormatProvider provider)
at System.String.System.IConvertible.ToType(Type type, IFormatProvider provider)
at System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider)
at fastJSON.JSON.ChangeType(Object value, Type conversionType) in c:\dev\MyCustomer-MyProject\trunk\MyProject\fastJSON\JSON.cs:line 422
at fastJSON.JSON.CreateDictionary(ArrayList reader, Type pt, Type[] types) in c:\dev\MyCustomer-MyProject\trunk\MyProject\fastJSON\JSON.cs:line 718
at fastJSON.JSON.ParseDictionary(Dictionary`2 d, Type type) in c:\dev\MyCustomer-MyProject\trunk\MyProject\fastJSON\JSON.cs:line 509
at fastJSON.JSON.ToObject(String json, Type type) in c:\dev\MyCustomer-MyProject\trunk\MyProject\fastJSON\JSON.cs:line 81
at fastJSON.JSON.ToObject[T](String json) in c:\dev\MyCustomer-MyProject\trunk\MyProject\fastJSON\JSON.cs:line 68
at MyProject.unit.test.UserDataTests.FooTest() in C:\dev\MyCustomer-MyProject\trunk\MyProject\MyProject.unit.test\UserDataTests.cs:line 110
Code that causes it:
public enum Numero
{
UNO, DOS, TRES
}
public class Foo
{
public Dictionary<Numero, bool> Dic { get; set; }
public Foo()
{
Dic = new Dictionary<Numero, bool>();
}
}
[Test]
public void FooTest()
{
Foo f = new Foo();
f.Dic[Numero.UNO] = true;
f.Dic[Numero.DOS] = false;
Console.WriteLine(JSON.Instance.ToJSON(f));
Assert.AreEqual(f, JSON.Instance.ToObject<Foo>(JSON.Instance.ToJSON(f)));
}
The Json that is produced for the dictionary field is:
"Dic":[{"k":"UNO","v":true},{"k":"DOS","v":false}]}
|
|
|
|

|
When loading from JSON, if an enum property has no value, fastJSON assigns it the first enum value.
For instance:
enum Numero { UNO, DOS, TRES }
class Foo {
public string Word {get;set;}
public Numero Num {get; set;}
}
The following JSON strings will be parsed into identical objects:
(1) { "Word": "schwing!" }
(2) { "Word": "schwing!", "Num": "UNO" }
If the enum's values were ordered differently, such as {TRES, DOS, UNO}, then string (1) above would set Num=TRES.
It would be nice if there was a little documentation of this. I had to write a test program to see how it worked.
|
|
|
|

|
Serialization and deserialization of datetime should use Utc (I use it to serialize/deserialize data through a WCF webservice and the server and the client are on different timezones)
My changes to the code are as follows:
In JSON.cs:
private DateTime CreateDateTime(string value)
{
int year = (int)CreateLong(value.Substring(0, 4));
int month = (int)CreateLong(value.Substring(5, 2));
int day = (int)CreateLong(value.Substring(8, 2));
int hour = (int)CreateLong(value.Substring(11, 2));
int min = (int)CreateLong(value.Substring(14, 2));
int sec = (int)CreateLong(value.Substring(17, 2));
return new DateTime(year, month, day, hour, min, sec, DateTimeKind.Utc).ToLocalTime();
}
private void ReadDataTable(ArrayList rows, DataTable dt)
{
dt.BeginInit();
dt.BeginLoadData();
var datetimeColumns = new List<int>();
foreach (DataColumn c in dt.Columns)
{
if (c.DataType == typeof (DateTime) || c.DataType == typeof (DateTime?))
{
datetimeColumns.Add(c.Ordinal);
}
}
foreach (ArrayList row in rows)
{
var v = new object[row.Count];
row.CopyTo(v, 0);
foreach (int i in datetimeColumns)
{
var s = (string) v[i];
if (s != null)
{
v[i] = CreateDateTime(s);
}
}
dt.Rows.Add(v);
}
dt.EndLoadData();
dt.EndInit();
}
In JSonSerializer.cs:
private void WriteDateTime(DateTime dateTime)
{
var dateTimeUtc = dateTime.ToUniversalTime();
_output.Append("\"");
_output.Append(dateTimeUtc.Year.ToString("0000", NumberFormatInfo.InvariantInfo));
_output.Append("-");
_output.Append(dateTimeUtc.Month.ToString("00", NumberFormatInfo.InvariantInfo));
_output.Append("-");
_output.Append(dateTimeUtc.Day.ToString("00", NumberFormatInfo.InvariantInfo));
_output.Append(" ");
_output.Append(dateTimeUtc.Hour.ToString("00", NumberFormatInfo.InvariantInfo));
_output.Append(":");
_output.Append(dateTimeUtc.Minute.ToString("00", NumberFormatInfo.InvariantInfo));
_output.Append(":");
_output.Append(dateTimeUtc.Second.ToString("00", NumberFormatInfo.InvariantInfo));
_output.Append("\"");
}
What do you think?
|
|
|
|

|
I want to pass classes with enum properties from my clients to my services, but the default DataContractSerializer throw exceptions.
thanks.
|
|
|
|

|
Dictionary<string, object> dict1 = new Dictionary<string,object>();
dict1.Add("foo", 42);
dict1.Add("bar", "hello");
string sJSON = fastJSON.JSON.Instance.ToJSON(dict1);
var dict2 = fastJSON.JSON.Instance.ToObject(sJSON);
Overall I'm loving this article and library, but I've hit a problem. The above code results in dict2 == null.
Stepping through the code the ParseArray() method returns this array
array
Count = 2
[0]: Count = 2
[1]: Count = 2
array[0]
Count = 2
[0]: {[k, foo]}
[1]: {[v, 42]}
array[1]
Count = 2
[0]: {[k, bar]}
[1]: {[v, hello]}
ToObject(string json, Type type) attempts to cast this to Dictionary<string, object> and returns null.
Am I doing something wrong?
|
|
|
|

|
Hi, Can I use FastJson as a library on Windows Phone 7 (silverlight)?
|
|
|
|

|
Hey,
Is there any chance to get support for nullable enum properties? Right now fastJSON throws "Invalid cast from 'System.String' to 'whatever'" exception. Try to serialize/deserialize this class:
public class TestClass
{
public DayOfWeek? Day { get; set; }
}
Thanks for the article!
|
|
|
|
|

|
I have really enjoyed studying and testing this great facility ! A few notes I hope may be useful to other CP members: these comments are made based on a few hours of study and testing of fastJSON in VS 2010 Pro, with both fastJSON and my WinForms test-bed application set to compile against .NET 4.0 Client Profile:
1. I had the impression, from reading comments here ... and responses to them from the author ... that you could only serialize/deserialize Class 'public Properties: that impression is incorrect.
You can easily serialize any 'public variable type, as well as 'public Properties.
2. I was surprised to find I could serialize a test-class that did not have the [Serializable] attribute.
3. I had no problem ... based on the author's example of extending fastJSON to handle TimeSpan ... to also handle serializing/deserializing types 'Rectangle, and 'Point.
a. one thing I noticed was: I needed to make the call that registered the new types outside the fastJSON library code ... specifically: outside of JSON.cs ... : if I made the call inside the author's code, my WinForms test-bed appliction would throw an error at run-time of a variety I've not seen before: "Operation could destabilize the runtime."
I do not consider this a "bug" in fastJSON, but probably something related to fastJSON's singleton architecture ... or ... to my creating a static class to handle new type registration.
4. In order to 'keep my head on straight' while experimenting with fastJSON, I made one modification in the code in JSON.cs method ToJSON:
public string ToJSON(object obj,
bool enableSerializerExtensions,
bool enableFastGuid,
bool enableOptimizedDatasetSchema,
bool serializeNullValues)
{
if (!obj.GetType().IsClass)
{
System.Windows.Forms.MessageBox.Show("MG_JSON input not a Class !");
return string.Empty;
}
return new JSONSerializer(enableOptimizedDatasetSchema, enableFastGuid, enableSerializerExtensions, serializeNullValues, IndentOutput).ConvertToJSON(obj);
}
Those of you with heads on-straight may not need such strait-jackets Probably better practice to put a try/catch around the call to ToJSON.
Once again, many thanks to Mehdi Gholam for this excellent CP resource !
best, Bill
"Reason is the natural order of truth; but imagination is the organ of
meaning." C.S. Lewis
|
|
|
|

|
Hi Mehdi,
Many thanks for this useful, exceptionally well-written, tested, and documented, rapidly-evolving JSON library !
One small question: somehow I expected your library to support writing a JSON file. fastJSON.Serialize, and fastJSON.Deserialize, are, however, delegates, not methods.
Of course, it's trivial for me to write a file myself, but I wondered why your library doesn't support this. Is the end-user of your library meant to use these delegates ? If so, would appreciate a pointer to how they are used.
thanks ! Bill
"Reason is the natural order of truth; but imagination is the organ of
meaning." C.S. Lewis
|
|
|
|

|
Hi,
I have one question
var xxx = fastJSON.JSON.Instance.ToObject(fastJSON.JSON.Instance.ToJSON(new List<int>{1,2,3,4,5}));
Why the return value is null?
|
|
|
|

|
What is that "Version=1.0.0.0" used for? Is it possible to have some versioning for the classes?
|
|
|
|

|
string testStr = JSON.Instance.ToJSON(true);
bool b =(bool)JSON.Instance.ToObject(testStr);
The second line will throw a NullReferenceException.
|
|
|
|

|
dude, what's up with the code.
there is no "var" in plain C# ....
|
|
|
|

|
Hi, when I use notation "NameSpace1.MyClass" && "NameSpace2.MyClass" fastJSON think that they are equals! Please, fix this bug. JSON.cs @@ -440,7 +440,7 @@ if (type == null) throw new Exception("Cannot determine type"); - string typename = type.Name; + string typename = type.FullName; object o = FastCreateInstance(type); SafeDictionary<string, myPropInfo> props = Getproperties(type, typename); foreach (string name in d.Keys)
|
|
|
|

|
Hi, I've added the following to this little beast
inside JSON.cs
private DataSet CreateTypedDataset(Dictionary<string, object> reader, Type t)
{
var ds = Activator.CreateInstance(t);
((DataSet)ds).Locale = CultureInfo.InvariantCulture;
((DataSet)ds).EnforceConstraints = false;
((DataSet)ds).BeginInit();
foreach (var pair in reader)
{
if (pair.Key == "$type" || pair.Key == "$schema") continue;
var rows = (ArrayList)pair.Value;
if (rows == null) continue;
var dt = ((DataSet)ds).Tables[pair.Key];
ReadDataTable(rows, dt);
}
((DataSet)ds).EndInit();
return (DataSet)ds;
}
and then inside private object ParseDictionary(Dictionary<string, object> d, Type type)
if (found == false && type.BaseType == typeof(DataSet))
{
return CreateTypedDataset(d, type);
}
Since strongly typed dataset already have the schema embedded we can serialize using
fastJSON.JSON.Instance.ToJSON(data, false, true, true, true)
deserialization is done by using:
fastJSON.JSON.Instance.ToObject<T>(json)
|
|
|
|

|
Hi,
really nice serializer.
I use it to serialize/deserialize strongly typed datasets.
there is one small problem. for multilanguage apps that set the currentculture of the current thread you must set
ds.Locale = CultureInfo.InvariantCulture; after
DataSet ds = new DataSet();
in private DataSet CreateDataset(Dictionary<string, object> reader) inside JSON.cs, otherwhise number/datetime conversion might fail.
I have one question. How to deserialize correctly a strongly typed dataset?
First I've tried the obvious:
fastJSON.JSON.Instance.ToObject<CustomerData>(json);
but it doesn't recognize it as a dataset.
It worked fine with (DataSet)fastJSON.JSON.Instance.ToObject(json, typeof(object));
but it's a little weird. Am I doing something wrong? Thanks.
modified on Thursday, July 7, 2011 10:29 AM
|
|
|
|

|
I am having problems converting this to an object structure due to multi array i think.
https://mtgox.com/code/data/getDepth.php[^][^]
the issue i think is the array inside the array. I actually wanted to read that inner array as a class instead of an array with a custom seriliser/deseriliser for the class but it did not get called as it is an array not a class.
Is there any way to read this data into objects without having to parse the data manually? Sadly i can change the json as i have no control of the source.
|
|
|
|

|
How does fastJSON handles object with circular reference? For example an Order has a list of OrderDetails, in which each has a reference back to its parent Order.
It seems fastJSON simply throw an exception when _MAX_DEPTH is reached. Any other better solution for this?
Thank you!
David
|
|
|
|

|
how generate jqGrid colmoder formatter function property like:
[{ name:"col1", formatter: function(v) {
return v;
}
} ]
function definition
@"function(v) {
return v;
}"
is multi-line user-defined skript retrieved form database at runtime.
.NET jsonserializer Serialize() method renders formatter in quotes and encodes characters like return, line feed, ", < and > producing invalid javasript code:
[{ "name":"col1", "formatter": "function(v) \r\n { return v; \r\n }" } ]
How to render formatter as normal javascript function definition ? Can fastjson or other serializer handle this ?
Andrus
|
|
|
|

|
I'm very new to Json but, as I understand things, it's a fairly compact text-based object notation. So if that's the case shouldn't this simple example work?
string before = "Hello World!"
string json = fastJSON.JSON.Instance.ToJSON(before);
string after = (string)fastJSON.JSON.Instance.ToObject(json);
Console.WriteLine ("Before: " + before + " After: " + after);
I must be missing something very simple...but what?
I was running fastJson 1.9.1
|
|
|
|

|
I have a class where a public property is null.
I set SerializeNullValues=false, and ToJSON() fails due to NullReferenceException.
Shouldn't the serializer simply ignore this null property? (Or maybe I don't understand how this setting is supposed to work.)
Here's the exception trace:
at fastJSON.JSONSerializer.WriteObject(Object obj) in C:\dev\myproj\trunk\proj\fastJSON\JsonSerializer.cs:line 242
at fastJSON.JSONSerializer.WriteValue(Object obj) in C:\dev\myproj\trunk\proj\fastJSON\JsonSerializer.cs:line 94
at fastJSON.JSONSerializer.WriteObject(Object obj) in C:\dev\myproj\trunk\proj\fastJSON\JsonSerializer.cs:line 256
at fastJSON.JSONSerializer.WriteValue(Object obj) in C:\dev\myproj\trunk\proj\fastJSON\JsonSerializer.cs:line 94
at fastJSON.JSONSerializer.ConvertToJSON(Object obj) in C:\dev\myproj\trunk\proj\fastJSON\JsonSerializer.cs:line 37
at fastJSON.JSON.ToJSON(Object obj, Boolean enableSerializerExtensions, Boolean enableFastGuid, Boolean enableOptimizedDatasetSchema, Boolean serializeNullValues) in C:\dev\myproj\trunk\proj\fastJSON\JSON.cs:line 58
at fastJSON.JSON.ToJSON(Object obj) in C:\dev\myproj\trunk\proj\fastJSON\JSON.cs:line 36
at proj.UserData.ToJSON() in C:\dev\myproj\trunk\proj\proj\UserData.cs:line 37
at proj.unit.test.UserDataTests.ToJSON() in C:\dev\myproj\trunk\proj\proj.unit.test\UserDataTests.cs:line 19
|
|
|
|

|
I pulled your latest release and got these two compile errors:
'System.Data.DataTable' does not contain a definition for 'ReadXmlSchema' and no extension method 'ReadXmlSchema' accepting a first argument of type 'System.Data.DataTable' could be found (are you missing a using directive or an assembly reference?)
C:\dev\MarketDelta-Footprint\trunk\Footprint\fastJSON\JSON.cs - line 823
'System.Data.DataTable' does not contain a definition for 'WriteXmlSchema' and no extension method 'WriteXmlSchema' accepting a first argument of type 'System.Data.DataTable' could be found (are you missing a using directive or an assembly reference?)
C:\dev\MarketDelta-Footprint\trunk\Footprint\fastJSON\JsonSerializer.cs - line 174
Can you assist?
Thanks.
|
|
|
|

|
Really good ... always improving ... finally you add support for public fields ... great ...
I will make some new comparisson test ...
Nice job ...
|
|
|
|

|
Hi, Mehdi:
Very good implementation. It is clean and small.
Does fastJSON support window phone platform?
If not, do you have plan to implement it in the near future?
Regards,
|
|
|
|

|
Excellent work. Now make it obtainable by nuget please
|
|
|
|

|
Hi!
I like fastJSON, i want write a custom javascriptConverter to convert every business objects to json, but Serialize function of JavaScriptConvert return a IDictionary(Of String, Object) and fastJSON return a json string?
Please give me a solution.
|
|
|
|
|

|
What a great article with superb detail! Thank you.
What approach would you recommend for implementing fastJSON in a MVC3/Silverlight setup?
I believe that if you create a nugget (www.nuget.org) fastJSON package; the adoption of fastJSON would skyrocket.
A "four-fecta" (a perfect scenario) could be MVC-REST/Silverlight/JSONP(callbacks)/fastJSON setup.
I am certain one could slam lots of data with mind-blowing speeds with fastJSON. I'm just concerned how easy a MVC/fastJSON(p) implementation could be.
Thoughts?
|
|
|
|

|
Excellent article!
Thanks for sharing.
|
|
|
|

|
I know you are busy with other stuff, but another thing for you to consider. TimeSpan serializes without value to:
{"$type":"System.TimeSpan, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"}
Not sure the best way to fix this?
|
|
|
|

|
Ok, never seen this error before
I'm doing .ToJson on an object as a result of a mvvmLight message being received...
{System.Security.VerificationException: Operation could destabilize the runtime.
at _(Object )
at fastJSON.JSONSerializer.WriteObject(Object obj)
at fastJSON.JSONSerializer.WriteValue(Object obj)
at fastJSON.JSONSerializer.WritePair(String name, Object value)
at fastJSON.JSONSerializer.WriteObject(Object obj)
at fastJSON.JSONSerializer.WriteValue(Object obj)
at fastJSON.JSONSerializer.WriteArray(IEnumerable array)
at fastJSON.JSONSerializer.WriteValue(Object obj)
at fastJSON.JSONSerializer.WritePair(String name, Object value)
at fastJSON.JSONSerializer.WriteObject(Object obj)
at fastJSON.JSONSerializer.WriteValue(Object obj)
at fastJSON.JSONSerializer.WriteArray(IEnumerable array)
at fastJSON.JSONSerializer.WriteValue(Object obj)
at fastJSON.JSONSerializer.WritePair(String name, Object value)
at fastJSON.JSONSerializer.WriteObject(Object obj)
at fastJSON.JSONSerializer.WriteValue(Object obj)
at fastJSON.JSONSerializer.ConvertToJSON(Object obj)
at fastJSON.JSON.ToJSON(Object obj, Boolean enableSerializerExtensions, Boolean enableFastGuid, Boolean enableOptimizedDatasetSchema, Boolean serializeNullValues)
at fastJSON.JSON.ToJSON(Object obj)
at Ultra.IsoDatabase.IsoDatabase.Save(Object obj, String key)
at vcpSL.ViewModel.CallCenterViewModel.Pulse(PulseMessage obj)
at GalaSoft.MvvmLight.Helpers.WeakAction`1.Execute(T parameter)
at GalaSoft.MvvmLight.Helpers.WeakAction`1.ExecuteWithObject(Object parameter)
at GalaSoft.MvvmLight.Messaging.Messenger.SendToList[TMessage](TMessage message, IEnumerable`1 list, Type messageTargetType, Object token)
at GalaSoft.MvvmLight.Messaging.Messenger.SendToTargetOrType[TMessage](TMessage message, Type messageTargetType, Object token)
at GalaSoft.MvvmLight.Messaging.Messenger.Send[TMessage](TMessage message)
at vcpSL.Messages.PulseMessage.Send()
at vcpSL.ViewModel.ApplicationSettings.<.ctor>b__0(Object s, EventArgs e)
at MS.Internal.CoreInvokeHandler.InvokeEventHandler(Int32 typeIndex, Delegate handlerDelegate, Object sender, Object args)
at MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex, Int32 actualArgsTypeIndex, String eventName)}
|
|
|
|

|
Hi there,
Been doing lots with the Sterling database
http://sterling.codeplex.com[^]
Could you have the same ability to decorate your class with ignore attributes of fields so they don't get serialised?
[JsonIgnore]
public string MyString {get;set;}
wouldn't get serialised for example
Many Thanks
Paul
|
|
|
|

|
Hi, folks
I have been testing with NETCF and mono Cecil but can't get them to work properly, I was hoping the win phone 7 would be as accomedating as silverlight 4 but it's not and has the same problems as netcf 3.5.
Any way I can release a version with slow reflection in the mean time until a work around is found, let me know what you think.
Cheers,
Its the man, not the machine - Chuck Yeager
If at first you don't succeed... get a better publicist
|
|
|
|

|
The subject says it all
Alberto Silva
|
|
|
|

|
When JSON is needed in my project I will give this a try - Great work.
|
|
|
|

|
Excellent and well-balanced article!
|
|
|
|

|
Fast and small, i�m using it in my framework.
http://lessframework.codeplex.com/documentation
Keep the good job.
|
|
|
|

|
Mehdi,
Many thanks for a great job on fastJSON!! Works great with generic classes. In the attached test program, ran into trouble when I attempted to deserialize a class which was derived from a generic class. Not a big deal really, since one can easily code around it. Just thought you might like to know...
In the attached C# code, if I add a member of type: class Telephones: List< Telephone >
to class: NameAndAddress and create a populated NameAndAddress instance, JSON.Instance.ToJSON() works OK. However,
the call to JSON.Instance.ToObject<NameAndAddress>() throws an exception:
at JSON.cs line 397 pi.setter(o,set);
Invalid Cast Exception was unhandled - unable to cast object of type 'System.Object[]' to type 'fastJSON.Telephones'.
Here's the code...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using fastJSON;
namespace fastJSonTest
{
public enum enumStates
{
es_Connecticut = 0x001,
es_Massachusetts = 0x002,
es_NewHampshire = 0x003
};
public enum enumTelephone
{
et_Undefined = 0x000,
et_Home = 0x001,
et_Work = 0x002,
et_Mobile = 0x003
};
public class Telephone
{
public enumTelephone Type { get; set; }
public string AreaCode { get; set; }
public string Exchange { get; set; }
public string Branch { get; set; }
public string Extension { get; set; }
public Telephone()
{
Type = 0x000;
}
public Telephone( enumTelephone et, string strAreaCode, string strExchange, string strBranch, string strExtension = null )
{
Type = et;
AreaCode = strAreaCode;
Exchange = strExchange;
Branch = strBranch;
Extension = strExtension;
}
};
public class NameAndAddress
{
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public string Street { get; set; }
public string City { get; set; }
public enumStates State { get; set; }
public List< Telephone > Telephones { get; set; }
public string E_Mail { get; set; }
};
class Program
{
static void Main( string[] args )
{
List< Telephone > telephones = new List< Telephone >();
Telephone telephone = new Telephone( enumTelephone.et_Mobile,
"xxx",
"xxx",
"xxxx" );
telephones.Add( telephone );
telephone = new Telephone( enumTelephone.et_Work,
"yyy",
"yyy",
"yyyy" );
telephones.Add( telephone );
telephone = new Telephone( enumTelephone.et_Home,
"zzz",
"zzz",
"zzz" );
telephones.Add( telephone );
NameAndAddress nanda = new NameAndAddress();
nanda.FirstName = "aaaa";
nanda.MiddleName = "bbbb";
nanda.LastName = "cccc";
nanda.Street = "XX ... Street";
nanda.City = "DDDD";
nanda.State = enumStates.es_Massachusetts;
nanda.E_Mail = "...@...";
nanda.Telephones = telephones;
JSON.Instance.UseFastGuid = true;
JSON.Instance.UseOptimizedDatasetSchema = true;
JSON.Instance.UseSerializerExtension = true;
string strJSON = JSON.Instance.ToJSON( nanda );
Console.WriteLine( "Name and address in JSON format:" );
Console.WriteLine( "" );
Console.WriteLine( strJSON );
var varTemp = JSON.Instance.ToObject<NameAndAddress>( strJSON );
NameAndAddress nanda1 = varTemp as NameAndAddress;
if ( null != nanda1 )
{
Console.WriteLine( "Name and Address from JSON format:" );
Console.WriteLine( "" );
Console.WriteLine( nanda1.ToString() );
}
}
}
}
|
|
|
|
 |
|
|
General News Suggestion Question Bug Answer Joke Rant Admin
|
Smallest, fastest polymorphic JSON serializer (with Silverlight4 and MonoDroid support)
| Type | Article |
| Licence | CPOL |
| First Posted | 19 Feb 2011 |
| Views | 1,600,073 |
| Downloads | 26,656 |
| Bookmarked | 467 times |
|
|