|
|
Comments and Discussions
|
|
 |

|
Nice have 5 from me. Could you kindly include a demo on how to use raptordb.
Thanks
|
|
|
|

|
Thank you ... Good job ... I needed a VB version so I converted some of the code to VB.NET ... The code can be found in the Issue tracker at fastjson.codeplex.com
|
|
|
|

|
I wanted to use this code to deserialize an array of objects and as written it just returns null.
The code I was attempting to use was:
string jsonstring = "[{ ...... }, {.....}]"; // edited for brevity
MyObjectType[] ar = fastJSON.JSON.Instance.ToObject( jsonstring );
This results in null because the intermediate form of the parsed data is an ArrayList but the ToObject method is expecting the input to always be an object not an array. The result is 'as' casted to a Dictionary which causes a null to be passed to ParseDictionary(). If a hard cast was used I guess it would throw an exception instead but currently just fails without errors. I have made the following modification to the ToObject(string, type) method in JSON.cs to make my use case work.
public object ToObject( string json, Type type )
{
object jsonobj = new JsonParser( json ).Decode();
if( jsonobj == null )
{
return null;
}
if( type != null && type.IsArray )
{
if( jsonobj is ArrayList )
{
return CreateArray( (ArrayList)jsonobj, type, type.GetElementType(), null );
}
else
{
throw new Exception( "Conversion to array type was requested but the JSON input was not parsed to an array" );
}
}
else
{
return ParseDictionary( (Dictionary<string, object>)jsonobj, null, type );
}
}
|
|
|
|

|
fastJSON.JSON.Instance.ToObject("[\"test\",\"string\"]") returns null.
Am I calling this incorrectly?
|
|
|
|

|
I'm a bit new to JSON, I was wondering what steps I should take to begin parsing something that looks like:
{
"POLINFO" : {
"NM" : "RTN",
"ID" : "",
"HC" : null
},
"MIR" : null,
"IG" : [{
"T" : null,
"F" : "a$",
"S" : "a$"
"TP" : "a$",
}, {
"T" : null,
"F" : "a$",
"S" : "a$"
"TP" : "a$",
}, {
"T" : null,
"F" : "a$",
"S" : "a$"
"TP" : "a$",
}, {
"T" : null,
"F" : "a$",
"S" : "a$"
"TP" : "a$",
}, {
"T" : null,
"F" : "a$",
"S" : "a$"
"TP" : "a$",
}, {
"T" : null,
"F" : "a$",
"S" : "a$"
"TP" : "a$",
}
],
"SI" : {
"NST" : "1",
"SST" : null
},
"ISO" : false,
"A2C" : "",
"A2CBT" : "",
"CI" : {
"CI" : "",
"PN" : "",
"PID" : "",
"SOURCE" : ""
},
}
Anything can help. I created a class that mimics the data entries so that I can enter it into the overloaded Quote: fastJSON.JSON.Instance.ToObject(Document, typeof(JSONTEST));
but I think I need to define a dictionary to map variables with the stated values still. I don't know how to do that though. Thanks for your time.
|
|
|
|

|
Thanks for sharing
|
|
|
|

|
I have a problem with deserialization. My code is
var obj = new Dictionary<string, string>() { { "Process", "ProcName" } };
string json = JSON.Instance.ToJSON(obj);
var obj2 = JSON.Instance.Parse(json);
And last string throws an exception "Could not find token at index 15".
When this option is used
JSON.Instance.UseSerializerExtension = false;
all works fine.
And second question: why you made serializer as singleton? In some cases I would like to change serialization options (only for one specific case), so making JSON constuctor public would be great.
|
|
|
|

|
Hi Mehdi, I'm approaching your library for the first time.
I have the following issue:
abstract class A { string MyProp { get; set; } }
class Aimpl : A { ... }
class Program
{
public void main()
{
A temp = new Aimpl();
temp.MyProp = "my content";
Console.WriteLine(fastJSON.JSON.Instance.ToJSON(temp));
}
}
The output json makes reference to the Aimpl class (something like {"$types":{"MyNameSpace.Aimpl, ...":"1"},"$type":"1", "MyProp":"my content"}), but I need to have a json referencing A class (something like {"$types":{"MyNameSpace.A, ...":"1"},"$type":"1", "MyProp":"my content"}) because I need to pass this json to a client where the Aimpl class is not available, but only the A class...
Is there a way to obtain the reference to the A class in the resulting json string?
Thank you very much for your support, and most of all for your terrific library!
Best
cghersi
|
|
|
|

|
I have a class that has 2 objects in it, call it MYdocument. MyData _sd which only has a bunch of Strings and Booleans, and _history that was a Stack. At first i was able to serialize and deserialize the object, but when I started using the _history object it started failing, in JSON.ParseDictionary(Dictionary d) on the line [setter(o, oset);]. I figured it was the Stack object and changed it to a Dictionary containing a version string as the key and a JSON of the _sd object.
String json = fastJSON.JSON.Instance.ToJSON(_sd); is returning an incomplete JSON object ->
"{\"$type\":\"MYdocument+MyData, MyProject, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null\",}"
_sd is just an object with private String and Boolean values, approx 30 of them.
When it was working, I noticed that the strings being generated don't seem to be staying true to the JSON format, a section of the value pairs:
"Title":"David""Version":"v.1.0.4""Date":"11/25/2011 10:11:07 AM""Group":"DevTeam""BillingCode":"lkj""Liaison":"lkj""Priority":"Critical""Timeframe":"lkjlkj""Summary":"lkj""Features":"lkj"
none of the key:value pairs are comma separated as I think it's stated in the JSON Specification. I plan on using the JSON objects with other C++, JavaScript, and Object C projects and am worried they won't deserialize properly.
Also all of the items are using the property get/set names, and not the actual varible names ex: _applicationTitle is the actual variable name in the class, and Title is the property get/set name.
|
|
|
|

|
Hi! I'll probably make a change from using XML to JSON in my metadata after knowing about your serializer. It's simply great!
After some tests, I've got a suggest for you: I'm using a lot of polymorphism in my classes, so, I need to use always the type notation serialization. Then, I've got a text where a huge part of it is composed of some type/assembly sentences repeated again and again along all the file, and I think there could be a simply way to compress all that data in a more efficient way.
I saw you've used a Dictionary to buffer all the types, both in serialize and when parsing... What do you thing about to save that dictionary as something like a header in the file and use only a key in every object? also, a lot of the types uses the same assembly, same version, same token, so, this header could also be writed in cascade and be very short.
I'm tempted to modify the code by myself, but I'm sure you'll do it much better... it's your code!
Thanks for your great code.
Best regards,
Marc Baye
|
|
|
|

|
Nice Article
|
|
|
|
|

|
It appears that it isn't possible to serialize anything containing self/mutual references. Any plans on implementing this? It would have to be an extension using an $id for every reference type object, and a $ref value when an object reoccurs.
|
|
|
|

|
I have a Dictionary.
The second string is a serialized Dictionary.
This serializes as:
{
"NetworkShell.ViewModels.ShellModel":"
[
{"k":"Height","v":680},
{"k":"Top","v":327},
{"k":"Width","v":1010},
{"k":"Left","v":1754}
]",
"NetworkShell.ViewModels.LoggerModel":"
[
{"k":"MinimumLevel","v":"Error"}
]"
}
When trying to dezsialize it in the first step to Dictionary, I get a run time error.
I think it is because the serialized string is not escaped?
|
|
|
|

|
The line public bool isCustomType; in JSON.cs (very last version) needs to be removed — it is unused and causes warning. Please do it.
—SA
Sergey A Kryukov
|
|
|
|

|
@@ -31,6 +31,7 @@ public bool SerializeNullValues = true; public bool UseUTCDateTime = false; public bool ShowReadOnlyProperties = false; + public bool IgnoreCase = false; public string ToJSON(object obj) { @@ -214,7 +215,7 @@ d.CanWrite = p.CanWrite; d.setter = CreateSetMethod(p); d.getter = CreateGetMethod(p); - sd.Add(p.Name, d); + sd.Add(IgnoreCase ? p.Name.Lower() : p.Name, d); } FieldInfo[] fi = type.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo f in fi) @@ -222,7 +223,7 @@ myPropInfo d = CreateMyProp(f.FieldType, f.Name); d.setter = CreateSetField(type, f); d.getter = CreateGetField(type, f); - sd.Add(f.Name, d); + sd.Add(IgnoreCase ? f.Name.ToLower() : f.Name, d); } _propertycache.Add(typename, sd); @@ -458,7 +459,7 @@ continue; } myPropInfo pi; - if (props.TryGetValue(name, out pi) == false) + if (props.TryGetValue(IgnoreCase ? name.ToLower() : name, out pi) == false) continue; if (pi.filled == true) {
|
|
|
|

|
It works perfectly and is the only (de)serializer that can successfully serialize complex and "exotic" types like Dictionary. It can also be used in applications for WP7, so I'll use it there, too.
|
|
|
|

|
It seems that Silverlight 5.0 is stricter about using the Array.CreateInstance as it really shouldn't have worked, due to Silverlight not supporting many of the generic arrays, etc.
Thus when using FastJSON in Silverlight 5.0 you need to update the CreateArray function to something like this:
private object CreateArray(List<object> data, Type pt, Type bt) {
var listType = typeof(List<>).MakeGenericType(new[] { bt });
var listOfCustom = Activator.CreateInstance(listType);
foreach (object ob in data) {
if (ob is IDictionary)
listType.GetMethod("Add").Invoke(listOfCustom, new[] { ParseDictionary((Dictionary<string, object>)ob, bt) });
else
listType.GetMethod("Add").Invoke(listOfCustom, new[] { ChangeType(ob, bt) });
}
return(listType.GetMethod("ToArray").Invoke(listOfCustom, null ));
}
|
|
|
|

|
HI, I come across an exception when I try to deserialize a class that contains a Dictionary.
The Exception Message is (I'm using SharpDevelop):
System.Exception: Failed to fast create instance for type 'myProject.ConversionTable' from assemebly 'myProject.ConversionTable,
myProject, Version=1.0.0.0, Culture=neutral, PublicKeyToken=a7dbcf259198817c' ---> System.ArgumentNullException: Value cannot be
null.
at System.Reflection.Emit.DynamicILGenerator.Emit(OpCode opcode, ConstructorInfo con)
at fastJSON.JSON.FastCreateInstance(Type objtype) in d:\SharpDevelop Projects\myProject\myProject\fastJSON149\JSON.cs:line 152
--- End of inner exception stack trace ---
at fastJSON.JSON.FastCreateInstance(Type objtype) in d:\SharpDevelop Projects\myProject\myProject\fastJSON149\JSON.cs:line 161
at fastJSON.JSON.ParseDictionary(Dictionary`2 d, Type type) in d:\SharpDevelop Projects\myProject\myProject
\fastJSON149\JSON.cs:line 451
at fastJSON.JSON.ToObject(String json, Type type) in d:\SharpDevelop Projects\myProject\myProject\fastJSON149\JSON.cs:line 82
at fastJSON.JSON.ToObject(String json) in d:\SharpDevelop Projects\myProject\myProject\fastJSON149\JSON.cs:line 74
at myProject.MainForm..ctor() in d:\SharpDevelop Projects\myProject\myProject\MainForm.cs:line 60
at myProject.Program.Main(String[] args) in d:\SharpDevelop Projects\myProject\myProject\Program.cs:line 25
The definition of the class is:
namespace myProject
{
public class ConversionTable
{
public ConversionTable(string jsonFilePath)
{
this.FilePath = jsonFilePath;
this.Table = new Dictionary<byte, byte>();
}
public ConversionTable(string TableName, string TableDescription)
{
this.Name = TableName;
this.Description = TableDescription;
this.Table = new Dictionary<byte, byte>(){{0x40,0x44}};
this.FilePath = this.Name.ToLower() + ".cfg";
}
public string FilePath;
public string Name {get; set;}
public string Description {get; set;}
public Dictionary<byte, byte> Table {get; set;}
}
public class Config
{
public Config(string ConfigDirectory)
{
this.Directory = ConfigDirectory;
this.ConversionTables = new List<ConversionTable>();
}
public string Directory {get; set;}
public List<ConversionTable> ConversionTables {get; set;}
}
}
After these lines, the value of 'cts' is null:
fastJSON.JSON.Instance.IndentOutput = true;
fastJSON.JSON.Instance.SerializeNullValues = false;
string jsonText = fastJSON.JSON.Instance.ToJSON(config.ConversionTables);
MessageBox.Show(jsonText, "ConversionTables as JSON");
List<ConversionTable> cts = (List<ConversionTable>)fastJSON.JSON.Instance.ToObject(jsonText, config.ConversionTables.GetType());
I get an exception when I try to serialize only one 'ConversionTable', and I get null as result of deserialization when I try to deserialize a list of 'ConversionTable's (List<ConversionTable>).
I'm using the latest version of fastJSON (1.9.4).
Please help me. What am I doing wrong?
modified 28 Oct '11 - 18:10.
|
|
|
|

|
How to parse object array?
|
|
|
|

|
Hi, I like your JSON de/serializer but I am having a few problems.
First, I don't understand why Dictionaries are serialized into:
"testDict":[
{
"k":"testKey1",
"v":[
{
"k":"testNestedKey1",
"v":53
}
]
}
]
instead of the correct way:
"testDict":
{
"testKey1":
{
"testNestedKey1" : 53
}
}
Also, I am getting an exception due to the nested Dictionary on line 422 in JSON.cs:
An unhandled exception of type 'System.InvalidCastException' occurred in mscorlib.dll
Additional information: Object must implement IConvertible.
Thanks in advance!
P.S. Is there a way to turn on pretty formatting? It seems to be all on one line when printed out to the console. (The examples above were formatted with an online tool).
|
|
|
|

|
Hi,
It seams the indentation bug in some case.
Adding a "_current_depth++;" at the beginning of "private void WriteObject(object obj)" seams to fix the pb.
Bye.
|
|
|
|

|
/*
* NOTE: I originally wrote this class as below with one public variable.
* Seems as all I wanted to do was to wrap up a Dicitonary which fastJSON
* cannot serialise unless it's a member of a class.
*
* This works fine under .Net code running in a winforms app or a WFC
* web service.
*
* HOWEVER it does not work in a Silverlight application, causing the
* following exception in JSON::CreateGetField
*
* Attempt by security transparent method 'fastJSON.JSON.CreateGetField(System.Type, System.Reflection.FieldInfo)'
* to access security critical method
* 'System.Reflection.Emit.DynamicMethod..ctor(System.String, System.Type, System.Type[], System.Type, Boolean)' failed.
*
* So instead the public member needs to be made private and wrapped up
* as a property. Which of course is best practice anyway!
[DataContract]
public class NameValueDictionaryContainer
{
public Dictionary<string, string> Dictionary;
}
*/
/// <summary>
/// In order to use fastJSON to serialise a dictionary it needs to be wrapped up within a containter oject
/// Not sure why, but the author said it was by design
///
/// This assmebly can be compiled for .net and silverlight and used on both client and server
/// </summary>
[DataContract]
public class NameValueDictionaryContainer
{
public NameValueDictionaryContainer()
{
}
private Dictionary<string, string> m_dict;
[DataMember]
public Dictionary<string, string> Dictionary
{
get { return m_dict; }
set { m_dict = value; }
}
}
|
|
|
|

|
After a >lot< of testing, I can add to Mehdis performance comments (in this context at least):
do{...}while(true) is faster than repeat:{...}goto repeat;
do{...}while(true) is faster than for (;true;){...}
for (;true; index++){...} is faster than do{}{...;index++;}while(true)
for (;compare;) is faster than while(compare)
pushing large arrays onto stack is slow
new'ing StringBuilder is slow
new'ing StringBuilder with size is >very< slow (per Mehdi)
checking for char[] index overflow is slow!!
- for speed, use the system exception (and maybe catch and re-raise)
On this last point, Mehdi's code checks for array overflow in various places and throws on overflow.
About 10-12% can be shaved off decoder times if you let the system throw the exception and remove the overflow checks.
If you want an app meaningful exception, catch the system exception (outside the loop) and map it to whatever you need.
Enjoy.
|
|
|
|

|
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)
|
|
|
|
 |
|
|
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,555,292 |
| Downloads | 25,748 |
| Bookmarked | 462 times |
|
|