|
|
Comments and Discussions
|
|
 |

|
Hi again,
Not sure if this is a bug but I found that in my case, fastJson (latest) was not deserializing the data serialized by WCF DataContractSerializer. Maybe I have missed something?
We have a website using NewtonSoftJson. This is "called into" by external websites(one .Net 3.5 SP1 and one .Net 4.0) via cookies which happen to use WCF DataContractSerializer for serialializations.
In my tests where the serializer/deserializer were fastJson, all was good. So I had replaced NewtonSoftJson in our project with fastJson. That's when I saw that the data coming in from these external apps was not being de-serialized correctly by fastJson.
The data structure is as follows:
public class XYZ
{
public const string cookieName = "dummy";
[DataMember(Name = "f1")]
public string f1 { get; set; }
[DataMember(Name = "f6Url")]
public string f6Url{ get; set; }
[DataMember(Name = "f7")]
public string f7{ get; set; }
[DataMember(Name = "f8")]
public string f8{ get; set; }
[DataMember(Name = "f9")]
public string f9{ get; set; }
[DataMember(Name = "fBool")]
public string fBool{ get; set; }
public string f17Url{ get; set; }
}
Sorry, I could not create a test project. When I reverted back to either WCF DataContractSerializer or NewtonSoftJson, all was good again. I am sure I might have missed something. Any thoughts?
|
|
|
|

|
I have some json strings with more fields than what I need. I'd like to end up with the same json strings, but with some of the fields removed.
Is there a way to deserialize to an object, then re-serialize and exclude some of the fields? Or is there a more performant way of doing this?
Also, is this page the best place to come for documentation or is there official documentation somewhere? Please forgive me if it's listed, I couldn't find it.
|
|
|
|

|
Do you have support for dynamic objects in fastJSON? It greatly helps in coding, especially when porting jscript to c#.
|
|
|
|

|
Good job there. I am trying to use this for nested classes that I have. In the sample below, it does not de-serialize what it has serialized. It is not able to create the object back after de-serialization. Why would that be?
class Program1
{
public class container
{
public string DataType;
public string Data;
}
public class setting
{
public Dictionary<string, string> basicCollection;
public string extraData;
}
public static void Main(string[] args)
{
setting s = new setting() { basicCollection = new Dictionary<string, string>(), extraData = "extra data value" };
s.basicCollection["key1"] = "value1";
s.basicCollection["key2"] = "value2";
container c = new container();
c.DataType = typeof(setting).ToString();
c.Data = fastJSON.JSON.Instance.ToJSON(s);
string serializedC = fastJSON.JSON.Instance.ToJSON(c);
container c1 = fastJSON.JSON.Instance.ToObject<container>(serializedC); Type t1 = Type.GetType(c1.DataType);
setting s1 = (setting)fastJSON.JSON.Instance.ToObject(c1.Data);
}
}
|
|
|
|

|
Good job on the article. Haven't looked at the code, but I'm intrigued. I've written some xml serializers before so I'm interested to checkout your code for JSON.
But I don't know what Stacks is? Can you provide a link? And yes, I've googled and found some promising links but I'm unsure if it's what you're referring to.
Thanks.
If your actions inspire others to dream more, learn more, do more and become more, you are a leader.-John Q. Adams You must accept one of two basic premises: Either we are alone in the universe, or we are not alone in the universe. And either way, the implications are staggering.-Wernher von Braun Only two things are infinite, the universe and human stupidity, and I'm not sure about the former.-Albert Einstein
|
|
|
|

|
Have you done any comparisons of using LINQ Expressions for generating your getters/setters code instead of using ILGenerator (which also requires the code using it to have elevated security privileges too if I'm not mistaken, where LINQ doesn't). Eg, I used LINQ Expressions to create accessors for private members, which you can see in this article[^]. I'd figure this would also allow the VM to optimize it since it's the one generating the IL from your high level expressions.
Also, why is 'myPropInfo' implemented as a struct (value type)? Not counting alignment padding, the structure is going has consume almost 50 bytes on a 32-bit platform (could be lessened with a Flags enum, but that still doesn't address my question about why it's a struct).
Every time you add or query an myPropInfo from your _propertycache, by definition the item retrieved should be a by-value copy of the stored 'myPropInfo', instead of a reference to. That just seems wasteful in terms of memory and execution performance, but if you have evidence to counter this assumption I'd like to see it (just as you've shown with all your other perf comparisons ).
edit: Also, wouldn't it be a tad more efficient to implement your CreateLong(string) method with an index and count parameter? In CreateDateTime you do a couple of value.Substring() calls. I would figure that you could just lose the extra string allocation from Substring and instead operating on the string's characters using its indexer instead of working on an enumerator.
It may also be better to have CreateInteger(out int/long num, string...) variants, at least for 32-bit platforms. Just to get rid of the extraneous 64-bit operations when you're dealing with ints (32-bits) in CreateDateTime (at least).
edit2: Looking more at the myPropInfo code, you have booleans for conditions which would be better suited in a 'type' Enum. Eg, isGuid vs isLong. A probably will only ever be one of those. Then in your 'ParseDictionary' method you could instead have a switch() statement that works on this hypothetical 'type' Enum's member for most of the if/else conditions, which would probably result in faster condition execution (assuming the JIT compiler generates an actual switch table in the assembly code)
edit3: I notice in some places you perform StringBuilder.Append calls on 1 character strings, instead of say an actual character (_output.Append("-") vs _output.Append('-')). Looking at the StringBuilder implementation for Append(string) and Append(char), it may prove to be slightly faster to use the char overload. While the string overload optimizes for strings which have 2 or less characters (and when there's enough free characters to append them), you would probably save a few cycles with the char overload due to fewer operations being done before the character is Append'ed
See for yourself:
public unsafe StringBuilder Append(string value)
{
if (value != null)
{
char[] chunkChars = this.m_ChunkChars;
int chunkLength = this.m_ChunkLength;
int length = value.Length;
int num3 = chunkLength + length;
if (num3 < chunkChars.Length)
{
if (length <= 0x2)
{
if (length > 0x0)
{
chunkChars[chunkLength] = value[0x0];
public StringBuilder Append(char value)
{
if (this.m_ChunkLength < this.m_ChunkChars.Length)
{
this.m_ChunkChars[this.m_ChunkLength++] = value;
}
else
{
this.Append(value, 0x1);
}
modified 13 Apr '13 - 20:25.
|
|
|
|

|
Hi
Could you update your benchmarks to either benchmark against the latest version of Json.NET or remove Json.NET from them all together.
Thanks
James
|
|
|
|

|
I have a class defined with an overloaded [] operator...for example:
public int this[int iX, int iY] { get { return m_aiData[iX,iY]; } set { m_aiData[iX,iY] = value;} }
However, the serializer seems to have a problem with this, giving me the exception "Common Language Runtime detected an invalid program."
I tested a variety of scenarios and this fails on *any* property of this type, unless of course I remove the "set", since it becomes read-only in that case and is ignored by fastJSON.
Is there any way around this? Is this something that can't be serialized? Of course I can make the property read-only and create a seperate function to "set" the values, but I'd really prefer not to, if possible. Thanks!
Edit: I forgot it doesn't handle n-dimension array, so I'll have to change some stuff anway But, I'd still like to have a definite answer.
modified 28 Mar '13 - 16:46.
|
|
|
|

|
*edit* I got this to work using (Dictionary)Parse(json), but documentation doesn't seem to support that this is how it should be done. For now, I am satisfied, but there is room for improvement with ToObject()
Hi. I'm reposting my question from CodePlex as I realized it isn't a very popular forum to communicate to you.
I'm working on a localization project and would like to deserialize a json string to a Dictionary in which some of the values may be another Dictionary for size optimization purposes (essentially namespacing). An example of the json is below.
{
"app": {
"title": "TITLE_EN",
"desc": "DESC_EN",
"settings": {
"" : "SETTINGS_EN"
"title": "SETTINGS_TITLE_EN"
}
}
}
I plan to end up with something I can recurse through and flatten down into a less complex Dictionary.
Unfortunately, attempts at using fastJSON.JSON.Instance.ToObject>(json) results in an exception in mscorlib's Dictionary.cs. According to jsonlint.com the string is valid json.
I had success using Parse(json) and ToObject(json), but it insists upon nesting IList which is undesirable to me. Do you have any recommendations on how to achieve this with fastJSON? Thanks for your hard work on this project.
modified 21 Mar '13 - 14:30.
|
|
|
|

|
Is there a way to serialize a collection of unknown-type objects, and determine their original type after de-serialization?
EG: object[] toSerialize = new[]{ new Guid() };
If I serialize the above, the serialized form doesn't store the GUID's type, and the GUID is de-serialized into a string.
Is there a way around this? Do I have to use generics / Tuple to accomplish this?
|
|
|
|

|
I hope you don't mind, but I created a fork of fastJSON:
https://github.com/kamranayub/fastJSON[^]
I added two features:
* RootElement support (it simply returns the first key match in the dictionary if present)
* Name variance (disabled by default)
I also organized the solution a bit because I had trouble getting everything running from your original source. I also pushed a Nuget package of my fork (different package name) so I could pull it into my project.
I separated the changes from the reorganization, so feel free to take a look at what I did. It would be great to see these updates in the core fastJSON! I just needed them right now.
|
|
|
|

|
One of the nice features of some other deserializers (RestSharp) is the ability to pass in a "root element" so you don't need to deserialize into a container class:
{
"person": {
"name": "Kamran"
}
}
fastJSON.JSON.Instance.ToObject<Person>(json, rootElement: "person")
This would be very helpful for REST APIs (or any service). Some APIs have useful containers (error, status, etc.) but the one I'm dealing with right now just adds a containing element for the heck of it.
-Kamran Ayub
|
|
|
|

|
Hi Mehdi,
first: thanks for fixing the problem with the edge case with nulls.
Now I run into the problem, that through a REST request I receive a Json string which is varies, depending on the request. The object contains a property for an id, which can contain one or more ids
- In case with one id, the property: is like "id": 123.
- In case of multiple ids, the property is: "id": "1234,12546,52344"
The problem is now: if only one id is passed (id=12) the parser throughs a cast error. The reason is, that fastJson uses a direct cast to convert the received object. Yet in the case of multiple values, the case is successful.
My question is now: why are you using a direct cast and not a ToString() method? With the ToString() method I can cover both scenarios.
Thanks for your input.
Chris
|
|
|
|

|
Would it be possible to update the version submitted to NuGet? It's 1.9.6 at the moment and you have fixed a number of bugs between then and now.
Kind thanks,
Roja
|
|
|
|

|
Concerning objects implementing IList or ICollection, all properties (other than items) are not serialized.
This snippet of serializer's code, seems to confirm this fact :
else if (obj is Array || obj is IList || obj is ICollection)
WriteArray((IEnumerable)obj);
Is it a normal behaviour ?
|
|
|
|

|
Hi,
I have a test-case which success to serialize, but fail to deserialize.
Here some code:
Class definitions:
[Serializable]
public class ConfigFormData
{
public Point Location { get; set; }
public Size Size { get; set; }
}
[Serializable]
public class ConfigData
{
public Dictionary<string, ConfigFormData> Forms { get; set; }
}
Usage:
ConfigData data = new ConfigData();
data.Forms = new Dictionary<string, ConfigFormData>();
data.Forms.Add(Name, new ConfigFormData(){Location = Location, Size = Size});
string json = fastJSON.JSON.Instance.ToJSON(data);
ConfigData data2;
data2 = fastJSON.JSON.Instance.ToObject<ConfigData>(json);
Json string:
{
"$types" : {
"WindowsFormsApplication2.Form1+ConfigData, WindowsFormsApplication2, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" : "1",
"WindowsFormsApplication2.Form1+ConfigFormData, WindowsFormsApplication2, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" : "2",
"System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" : "3",
"System.Drawing.Size, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" : "4"
},
"$type" : "1",
"Forms" : {
"Form1" : {
"$type" : "2",
"Location" : {
"$type" : "3",
"X" : 147,
"Y" : 147
},
"Size" : {
"$type" : "4",
"Width" : 384,
"Height" : 356
}
}
}
}
And the exception (in french, sorry):
Message: L'objet doit implémenter IConvertible.
Stack:
à System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider)
à fastJSON.JSON.ChangeType(Object value, Type conversionType)
à fastJSON.JSON.ParseDictionary(Dictionary`2 d, Dictionary`2 globaltypes, Type type, Object input)
à fastJSON.JSON.CreateStringKeyDictionary(Dictionary`2 reader, Type pt, Type[] types, Dictionary`2 globalTypes)
à fastJSON.JSON.ParseDictionary(Dictionary`2 d, Dictionary`2 globaltypes, Type type, Object input)
à fastJSON.JSON.ToObject(String json, Type type)
à fastJSON.JSON.ToObject[T](String json)
à WindowsFormsApplication2.Form1.button1_Click(Object sender, EventArgs e) dans D:\tmp\WindowsFormsApplication2\Form1.cs:ligne 46
|
|
|
|

|
Hi Mehdi,
I'm very impressed with your implementation here. Particularly your performance results - the results against BinaryFormatter are very telling - and the fact that you beat Stack. I prototyped my own binary serializer a few years ago (never went into production), that was around 40x faster than the binary serializer, so I can appreciate a text-based format beating the binary formatter.
I actually needed fastJSON for it's ability to deserialize the more complex OO types. I can't believe that Stack resisted your requests. Although it would be good to call your solution a JSON and JSONOO serializer, for clarity.
Also, I have thoughts of re-visiting my binary formatter, now called eXtensible Binary eXchange (XBX). I particularly want to use it with Javascript over WebSockets. I would build it open source, and it would be tunable and configurable, with default setup for fulfilling most applications, but able to be tuned to minimize payload and maximize performance.
Please contact me if you would like more details and would like to help. I can share my draft Google Doc and we could work on the specification first, and possibly co-author another codeproject article.
|
|
|
|

|
Hello everyone, I can not do with json decode, please help?
string jsonText = "[[{\"language\":\"es\",\"isReliable\":false,\"confidence\":0.4517133956386293},{\"language\":\"pt\",\"isReliable\":false,\"confidence\":0.08356545961002786}],[{\"language\":\"en\",\"isReliable\":false,\"confidence\":0.17017828200972449},{\"language\":\"vi\",\"isReliable\":false,\"confidence\":0.13673655423883319}]]}}";
var newobj = fastJSON.JSON.Instance.ToObject<List<SubFolder>>(jsonText);
private class SubFolder
{
public string language { get; set; }
public string isReliable { get; set; }
public string confidence { get; set; }
}
> the array would be this:
{"data":{"detections":[[{"language":"es","isReliable":false,"confidence" .4517133956386293},{"language":"pt","isReliable":false,"confidence" .08356545961002786}],[{"language":"en","isReliable":false,"confidence" .17017828200972449},{"language":"vi","isReliable":false,"confidence" .13673655423883319}]]}}
|
|
|
|

|
Im happy with this lib first of all,
but I recently found a bug
you can cast an int[][] from the json string "[[0,0,2]]"
Greetings
|
|
|
|

|
Hello, Just wanted to ask, if there are any plans of making fastJSON available to WinRT platform? Regards, Dovydas
|
|
|
|

|
Change fastJSON version from 1.9.6 to current version 2.0.13 and now I cannot longer deserialize classes with enum properties. Always get exception "InvalidCastException: Cannot convert type System.Int64 to type System.String".
Compiling fastJSON for .NET 2.0
Any ideas?
Best regards,
Markus
|
|
|
|

|
If jp.UseOptimizedDatasetSchema is set with false and the json text with dataset is handled by the method "Beautify", the dataset's xml schema in the json text will be not well-formed. I guess that the method of "Formatter.PrettyPrint" is not implemented correctly.
|
|
|
|

|
A bug !!! All objects must be declared with "public", otherwise, the exception - failed to fast create instance - will be threw during deserialization from JSON text.
|
|
|
|

|
I am having problems using fastJSON in my Silverlight 4 application.
When I call: fastJSON.JSON.Instance.ToJSON(myObject);
I get an exception here:
DynamicMethod getter = new DynamicMethod("_", typeof(object), new Type[] { typeof(object) }, type);
Exception:
Attempt by security transparent method 'fastJSON.Reflection.CreateGetMethod(System.Type, System.Reflection.PropertyInfo)' to access security critical method 'System.Reflection.Emit.DynamicMethod..ctor(System.String, System.Type, System.Type[], System.Type)' failed.
Do you have any idea how I could get this fixed?
I took the fastJSON-SL project and builded. Then added the .dll to my SL app.
Best Regards
Frederik
|
|
|
|

|
Can you compare performance with
|
|
|
|

|
I was reviewing some of the code and noticed that you target .NET 4.0 but are using monitor locks for dictionary access. This isn't altogether terrible, but figured you might like to know MS has added concurrency oriented collections and ConcurrentDictionary<K,V> might be to your liking. It also better encapsulates common atomic operations like GetOrAdd and AddOrUpdate. Besides that, the main reason I'm avoiding this for now is the lack of Stream support. I have network and file stream data that would be inconvenient to load into memory entirely (some rather large data at times). Since you're using a forward moving tokenizer I don't think this would be entirely too difficult using a TextReader. Thanks for the article and code
|
|
|
|

|
How does fastJson handle circular references? Json.Net has a setting that limits circular references whereas the .NET Json serializer throws an error but I did not see any mention in your article about handling circular references with fastJson.
If you could comment, I would appreciate it.
|
|
|
|
|

|
Line 328 in JsonSerializer.cs
maybe int c = g.Count; is int c = g.Count + 1; ?
test data is (type Test is struct):
Test data = new Test(1,"Test","Test");
serialized string is (but incorrect):
{"Id":1,"Name":"Test""Picture":"Test"}
after modifying source code:
{"Id":1,"Name":"Test","Picture":"Test"}
|
|
|
|

|
Consecutive NULL parameters in class, with SerializeNullValues = false produces multiple commas.
eg.
var objTest = new
{
A = "foo",
B = (object)null,
C = (object)null,
D = "bar"
};
jsonInstance = JSON.Instance;
jsonInstance.Parameters = new JSONParameters
{
EnableAnonymousTypes = false,
IgnoreCaseOnDeserialize = false,
SerializeNullValues = false,
ShowReadOnlyProperties = true,
UseExtensions = false,
UseFastGuid = true,
UseOptimizedDatasetSchema = true,
UseUTCDateTime = false,
UsingGlobalTypes = false,
UseEscapedUnicode = false
};
var json = JsonFormatter.JSON.ToJSON(objTest);
json = {"A":"foo",,"D":"bar"}
|
|
|
|

|
look at the code:
Version oVer = new Version("2012.12.12");
string sNewSer41 = fastJSON.JSON.Instance.ToJSON(oVer);
Version oTest41 = fastJSON.JSON.Instance.ToObject<Version>(sNewSer41);
sNewSer41 parameter is right.
but when deserialize it to Version instance,i find it can't success to deserialize.
Last One Code
|
|
|
|

|
look at this:
NameValueCollection oCollect = new NameValueCollection(2);
oCollect.Add("key1","value1");
oCollect.Add("key2","value2");
When call the method:
fastJSON.JSON.Instance.ToJSON(oCollect)
it can't get the right result.then i debug the source,finally i find the code in "JsonSerializer.cs" here:
if (obj is Array || obj is IList || obj is ICollection)
WriteArray((IEnumerable)obj);
in fact,NameValueCollection is a key/value collection,although it implement the ICollection interface.
so when NameValueCollection casted IEnumerable interface,it could only serialize NameValueCollection's key.
I think we can add one piece code before that code:
else if (obj is NameValueCollection)
WriteNameValueCollection((NameValueCollection)obj);
the WriteNameValueCollection() method can implement as IDictionary. it that right?
Last One Code
|
|
|
|

|
Hi Mehdi
I noticed that included in the solution there is a Mono for Android project. I also need to run the code on iOS (MonoTouch).
Since the use of reflection on iPhone is limited, I wonder what needs to be done to make fastJSON work without the "Emit" in Refelection.cs (and probably would be called "a little bit less fastJSON" )
I am not too familiar with Reflection Emit myself, but basically creating a slower (non-emit) version of FastCreateInstance, CreateSetField, CreateSetMethod, CreateGetField, CreateGetMethod would do the job ?
Thanks
Gerd
Edit : fastJASON => fastJSON
modified 18 Dec '12 - 18:07.
|
|
|
|

|
Hi Mehdi,
I noticed that Code Project lists this article and associated code as being under the CPOL (both on the right navbar and at the end of the article), while Codeplex (and as a result nuget) has fastJSON listed as GPLv2.
This may not be something that you can change here (I'm not too familiar with how it works) but am I right in thinking that it's intended to be under the GPL (ie allowing no commercial use in larger non-opensource works etc) instead of CPOL?
Many thanks!
|
|
|
|

|
I do get an exception at de line below : It seems as if the object 'v' is not a generic list but a generic dictionary .. any ideas on how to solve this ? Thanks! JSON.cs line 496 else if (pi.isGenericType && pi.isValueType == false && pi.isDictionary == false) oset = CreateGenericList((List<object>)v, pi.pt, pi.bt, globaltypes);
System.InvalidCastException: Cannot cast from source type to destination type. at fastJSON.JSON.ParseDictionary (System.Collections.Generic.Dictionary`2 d, System.Collections.Generic.Dictionary`2 globaltypes, System.Type type, System.Object input) [0x0026d] in /Users/Gerd/Documents/Documents/Business/Clients/Vendors/fastJSON_v2/fastJSON/JSON.cs:496 at fastJSON.JSON.ToObject (System.String json, System.Type type) [0x00155] in /Users/Gerd/Documents/Documents/Business/Clients/Vendors/fastJSON_v2/fastJSON/JSON.cs:163 at Mobiflow.PersistentAwsS3.LoadJson (System.Type type, System.String path, Mobiflow.LoadJsonFinished finished, System.Object[] parameters) [0x000d3] in /Users/Gerd/Projects/Mobiflow/Mobiflow/Nodes/Management/PersistentAwsS3.cs:389
|
|
|
|

|
in string : { "Name" : "Ali","Age" : 21, 256} throw Exception in method 'ParseString' : 'Unexpectedly reached end of string' because number of 256 has not name! May be solve it whitout define name?
|
|
|
|

|
Hi When I try Deserialize string like : { "Name" : "Ali","Age" : 21} Throw exception from file 'JSON.cs" in line 452 (in method 'ParseDictionary',condition 'type == null'). Where is error?
|
|
|
|

|
Hi, I'm looking at using fastJSON for our production system.
Right now I'm stuck on the deserializatiob of a Dictionary>
object. It serializes fine but when I deserialize the inner Dictionary is empty. Any ideas ?
Dictionary<string, Dictionary<string, string>> _allsettings = new Dictionary<string, Dictionary<string, string>>();
_allsettings.Add("test", new Dictionary<string, string>());
_allsettings["test"].Add("fn", "f1");
fastJSON.JSON.Instance.Parameters.UseExtensions = false;
fastJSON.JSON.Instance.Parameters.ShowReadOnlyProperties = true;
string sw = fastJSON.JSON.Instance.ToJSON(theobj);
_allsettings = fastJSON.JSON.Instance.ToObject<Dictionary<string, Dictionary<string, string>>>(sw);
Thanks
Garrett
p.s. this stuff is amazingly quick and works for most my data (except this1)
|
|
|
|

|
Hi Mehdi,
Impressive work there !
Actually, since you seem to master your serialization stuff pretty well, i was wondering if you could please have a look at a spec proposal i made here
JsonR(aw): Lightweight JSON Protocol Proposal[^]
and maybe consider adding serialization support for it ? It's been really beneficial for us at our company, and I'm sure others will find it interesting too.
There's a GitHub page up, with a small sample page showing off savings.
https://github.com/itechnology/JsonRaw[^]
Thank's for your time,
Robert
|
|
|
|
|

|
Hello,
First, let me say you have put some excellent work in your fastJSON (de)serializer!
I want to use fastJSON to replace the use of DataContractJsonSerializer in my project and I am wondering if fastJSON will support following features in the near future:
* (de)serialization of *some* private/protected properties (to control access to properties of the object)
* (de)serialization from/to streams (for example: direct deserialization of large (and gzipped) json objects over ethernet)
Thank you!
Regards
Gerd
|
|
|
|

|
Hi Mehdi,
Trying to use it in Monodev project.
The data returned:
{
"access_token":"example",
"token_type":"send",
"expires_in":3430,
"refresh_token":"refresh"
}
Here is the class definition:
[Serializable]
class TokenResponse
{
public String AccessToken
{
get;
set;
}
public String TokenType
{
get;
set;
}
public Int64 ExpiresIn
{
get;
set;
}
public String RefreshToken
{
get;
set;
}
}
If not using type as in :
var newobj = fastJSON.JSON.Instance.ToObject(returnedRawData);
Then getting an exception "Cannot determine type"
If using type as in :
fastJSON.JSON.Instance.Parameters.SerializeNullValues = true;
var newobj = fastJSON.JSON.Instance.ToObject<TokenResponse>(returnedRawData);
The newobj has the corrct names, but values are not populated.
Any ideas what I am missing,
Thanks
F.
|
|
|
|

|
I have a class with property called PenColors that is of type List<System.Windows.Media.Color>, so I registered a custom deserializer that called ColorConverter.ConvertFromString() to handle conversions for colors. Despite this, when deserializing I would always get an exception from the ChangeType() function in JSON.cs about an invalid cast from 'System.String' to 'System.Windows.Media.Color'. I did some digging and found that it worked fine if I used a simple Color property, but a List<Color>>would fail.
Looking at the code, the CreateGenericList() function calls ChangeType() to add items to the list, but ChangeType() doesn't consider if the type is a registered custom type and ultimately calls Convert.ChangeType() which can't handle Colors, so the conversion fails. I assume this means any custom type in a list would also fail, but I did not test anything other than Color. To fix this, I added the following to ChangeType():
else if (IsTypeRegistered(conversionType))
return CreateCustom((string)value, conversionType);
And now the issue is resolved. I'm not sure if that's the best way to go about it, but it's worked for me so far.
|
|
|
|

|
Hi,
i get some Data as String and just want them to deserialize to an object.
In a few cases i get "null" as json-value and the function "fastJSON.JSON.Instance.ToObject(null)" crashes.
Could you please fix this in the next releases? This would be really great, because checking everytime for "null" now isn't very comfortable.
Thank You!
|
|
|
|

|
how does the output size compare?
to json.net , servicestack.text...
also what about memory usage while serializing,deserializing?
also is there features that json.net or servicestack.text that fastJson doesn't have?
thanks
|
|
|
|

|
Hi Mehdi,
I made a simple application just to test my class conversion. Serialization works great, unfortunatelly I cannot deserialize that very same json text to my object, I get the above error message.
I'm not an expert C# developer, so it might be easily that I did something wrong, can please point me to the right direction?
This would be my code. First I put JSON text create from OrderIn class into a textbox, then trying to deserialize that text back into OrderIn.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Text;
using System.Windows.Forms;
namespace fastJSON_experiment
{
public partial class Form1 : Form
{
public class OrderItemIn
{
public OrderItemIn(string itemnumber, string quantity)
{
ItemNumber = itemnumber;
Quantity = quantity;
}
public string ItemNumber { get; set; }
public string Quantity { get; set; }
}
public class OrderIn
{
public OrderIn()
{
Items = new List<OrderItemIn>();
}
public string Token { get; set; }
public string SAPSys { get; set; }
public string RequestID { get; set; }
public string MethodName { get; set; }
public List<OrderItemIn> Items { get; set; }
}
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OrderIn o = new OrderIn();
o = (OrderIn)fastJSON.JSON.Instance.ToObject(textBoxJSON.Text);
textBoxProperty.Text = o.MethodName;
}
private void button3_Click(object sender, EventArgs e)
{
textBoxJSON.Text = "";
OrderIn oi = new OrderIn();
oi.Token = "lunch33aught96parchduechis93gook61mist85cove";
oi.RequestID = "k32jk3kj2k23kh4";
oi.MethodName = "Simulationtest";
oi.SAPSys = "T15/105";
oi.Items.Add(new OrderItemIn("123456", "1"));
oi.Items.Add(new OrderItemIn("124456", "11"));
oi.Items.Add(new OrderItemIn("233456", "13"));
oi.Items.Add(new OrderItemIn("123456", "14"));
oi.Items.Add(new OrderItemIn("123456", "81"));
fastJSON.JSON.Instance.Parameters.UseExtensions = false;
textBoxJSON.Text = fastJSON.JSON.Instance.ToJSON(oi);
}
}
}
Thank you,
Tibor
|
|
|
|

|
Hi Mehdi,
I write simple tests:
public void SimpleTests()
{
#region ulong
var s = JSON.Instance.ToJSON(ulong.MaxValue);
var o = JSON.Instance.ToObject(s);
Assert.That(ulong.MaxValue, Is.EqualTo(o));
#endregion
#region float
s = JSON.Instance.ToJSON(float.MinValue);
o = JSON.Instance.ToObject(s);
Assert.That(float.MinValue, Is.EqualTo(o));
s = JSON.Instance.ToJSON(float.MaxValue);
o = JSON.Instance.ToObject(s);
Assert.That(float.MaxValue, Is.EqualTo(o));
#endregion
#region double
s = JSON.Instance.ToJSON(double.MinValue);
o = JSON.Instance.ToObject(s);
Assert.That(double.MinValue, Is.EqualTo(o));
s = JSON.Instance.ToJSON(double.MaxValue);
o = JSON.Instance.ToObject(s);
Assert.That(double.MaxValue, Is.EqualTo(o));
#endregion
#region decimal
s = JSON.Instance.ToJSON(decimal.MinValue);
o = JSON.Instance.ToObject(s);
Assert.That(decimal.MinValue, Is.EqualTo(o));
s = JSON.Instance.ToJSON(decimal.MaxValue);
o = JSON.Instance.ToObject(s);
Assert.That(decimal.MaxValue, Is.EqualTo(o));
#endregion
}
And all of them throw exceptions.
thanks for your feedback,
Gintas
|
|
|
|

|
Hi Mehdi,
I run following test:
[Test]
public static void ObjectWithNullPropertyTest()
{
var ds = new MultiValue();
ds.keys = new List<object>(){1,2,3,4,5};
ds.values = new List<string>(){"1", "2", "3", "4", "5"};
ds.keySel = 3;
ds.refId = new Guid();
fastJSON.JSONParameters param = new JSONParameters();
param.SerializeNullValues = false;
param.UseExtensions = false;
param.UseFastGuid = false;
var newJson = fastJSON.JSON.Instance.ToJSON(ds, param);
Assert.AreEqual(newJson, "{\"values\":[\"1\",\"2\",\"3\",\"4\",\"5\"],\"keys\":[1,2,3,4,5],\"keySel\":3,\"refId\":\"00000000-0000-0000-0000-000000000000\"}");
}
with the following objects:
public class SingleValue
{
public SingleValue()
{
}
public SingleValue(string value, Guid refId)
{
this.value = value;
this.refId = refId;
}
public string value { get; set; }
public Guid refId { get; set; }
}
public class MultiValue : SingleValue
{
public MultiValue()
{}
public MultiValue(List<string> values, List<object> keys, object keySel, Guid refId)
{
this.values = values;
this.keys = keys;
this.keySel = keySel;
this.refId = refId;
}
public List<string> values { get; set; }
public List<object> keys { get; set; }
public object keySel { get; set; }
}
The problem is, that there's a comma to much after the '"keySel":3, ,' I was able to solve the problem by commenting out the following two lines in the JsonSerializer.cs
...
else
{
WritePair(p.Name, o);
if (o != null && _params.UseExtensions)
...
My question is now: why is the 'if' statement in there? I couldn't follow the logic of it or the comment (last non null).
Thanks for your help,
Chris
|
|
|
|

|
Hi Mehdi,
I try to write simple test and it fails.
Here's my test code:
sbyte zero = 0;
s = JSON.Instance.ToJSON(zero);
o = JSON.Instance.ToObject(s);
Assert.That(zero, Is.EqualTo(o));
parser throws exeption:
System.IndexOutOfRangeException was unhandled by user code
HResult=-2146233080
Message=Index was outside the bounds of the array.
Source=fastJSON
StackTrace:
at fastJSON.JsonParser.ParseNumber() in d:\tmp\fastJSON\fastJSON\JsonParser.cs:line 293
at fastJSON.JsonParser.ParseValue() in d:\tmp\fastJSON\fastJSON\JsonParser.cs:line 122
at fastJSON.JsonParser.Decode() in d:\tmp\fastJSON\fastJSON\JsonParser.cs:line 46
at fastJSON.JSON.ToObject(String json, Type type) in d:\tmp\fastJSON\fastJSON\JSON.cs:line 143
at fastJSON.JSON.ToObject(String json) in d:\tmp\fastJSON\fastJSON\JSON.cs:line 128
at fastJSON.Tests.Tests.Testsbyte() in d:\tmp\fastJSON\fastJSON.Tests\Tests.cs:line 144
InnerException:
thanks for your feedback,
Gintas
|
|
|
|

|
hi Mehdi,
i'm converting values with special characters (i.e. German Umlaut, etc.) from Objects to Json. The problem is now, that those values are converted to utf-8 escaped character (i.e. ü ==> \\u00FC).
I was wondering, why those characters are escaped and if there's a way around it, without converting it after the serialization.
thanks for your help,
Chris
|
|
|
|
 |
|
|
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,557,121 |
| Downloads | 25,759 |
| Bookmarked | 462 times |
|
|