|
|
Comments and Discussions
|
|
 |

|
Hi Mehdi,
nice work! I run though into a problem, when I tried to deserialize a JSON into a polymporphic objects. My object model is similar to city => list<zoo> => list<animals>
Since I don't know what animals are within a zoo, I just have a type animal for each zoo. The problem is now, that only animals of type animal are created and not dogs, cats, etc.
Now, I would like to solve this problem through a custom type animal, in which I can check the supplied json for the necessary properties for each animal (dog barks, cat miaus, etc.)
The issue is now, that the current implementation (2.0.9) passes only a string to the custom deserializer and throws an error, if the custom type consist of multiple properties or additional object. I was now wondering if this could be changed to the passed parameter from string to a dictionary or full json object.
thanks for your feedback,
Chris
|
|
|
|

|
Hi Mehdi,
We are planning to use your work in our company. In that scope, I have done some major code review. For now, I can offer you two different packages, if you are interested: a small one and a big one.
The first is primarily focusing on the public API applies primarily minor code review changes. This should definitely a value to the community. Performance characterisics should not have been changed.
The second package is an intense review, in brief details:
- Harmonizing with .NET naming conventions
- Applying good principles like separation of concerns (with perf. in mind).
- Improving exception reporting
- Increasing flexibility of the framework: Property opt-in, Property opt-out. This should increase performance in real-life use cases.
- Small performance drop 1-3% (custo types always available)
- Unit test driven: all native serilization/ deserialization is tested (46+ Tests)
- 5+ Bug fixes
- Improved debugging capabilities
In the near future, I will have to make the basic funcionality again available under Silverlight 5. Which critical feature was removed by Microsoft?
Best Regards,
Aron
|
|
|
|

|
dynamic employee = new ExpandoObject();
employee.Name = "John Smith";
employee.Age = 33;
var manager = new ExpandoObject() as IDictionary<string, object>;
manager.Add("Name", "Allison Brown");
manager.Add("Age", 42);
Console.WriteLine(((string)fastJSON.JSON.Instance.ToJSON(employee)));
Console.WriteLine(fastJSON.JSON.Instance.ToJSON(manager));
Console.WriteLine(((string)ServiceStack.Text.JsonSerializer.SerializeToString(employee)));
Console.WriteLine(ServiceStack.Text.JsonSerializer.SerializeToString(manager));
Output:
{"$types":{"System.Dynamic.ExpandoObject, System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089":"1"},"$type":"1"}
{"$types":{"System.Dynamic.ExpandoObject, System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089":"1"},"$type":"1"}
["[Name, John Smith]","[Age, 33]"]
{"Name":"Allison Brown","Age":42}
|
|
|
|

|
I have a anoying problem.
I am getting this error now. It has been working before in other projects but not in my recent.
This is a test code that is thowing the error:
Public Class fastJSONBuggTestC
Public Settings As New SettingsC
Public Class SettingsC
Public Version As Integer = 1
Public RegistrationKey As String = "unknown"
End Class
Public Sub New()
Dim testSettings As New SettingsC()
Dim param As New fastJSON.JSONParameters()
param.IgnoreCaseOnDeserialize = True
param.SerializeNullValues = True
param.UseExtensions = True
param.UseFastGuid = True
param.UseOptimizedDatasetSchema = True
param.UseUTCDateTime = True
param.UsingGlobalTypes = True
Dim jsonString As String = fastJSON.JSON.Instance.ToJSON(Settings, param)
Settings = fastJSON.JSON.Instance.ToObject(jsonString)
End Sub
End Class
It is this row:
Settings = fastJSON.JSON.Instance.ToObject(jsonString)
that is throwing the error "Cannot determine type", anyone now why this is hapening now and not before?
Thanks!
Robin Andersson
|
|
|
|

|
Extremely through and highly optimized
|
|
|
|

|
A couple of examples:
One:
["foo0",{"foo1":"C:\\!bar1","foo2":"C:\\bar2"}]
[
"foo0",
{
"foo1" : "C:\\!bar1",
"foo2" : "C:\\bar2"}]
Two:
[{"foo":"'[0]"}]
[
{
"foo" : "'[
0
]"}]
|
|
|
|

|
Hi,
great work and I'd really appreciate it if you try to update the NuGet package regularly. So everyone can update to the latest version easyly.
Thanks a lot
|
|
|
|

|
like:
var arr2 = new[]{
new { Text = "M", Value = true},
new { Text = "F", Value = false }
};
var ttt = fastJSON.JSON.Instance.ToJSON(arr2, new fastJSON.JSONParameters() { UseExtensions = false });
the result is : "[{},{}]"
|
|
|
|

|
Hello,
I run the console test and it appears that deserialization of dataset is not working.
Was it working in a previous version?
Tkanks a lot.
|
|
|
|

|
For example i have code in c#:
public class TestB
{
public int b = 3;
public string c = "AA";
public TestB() { }
};
public class TestA
{
public int a = 0;
public TestB tb = new TestB();
public TestA() { }
};
void method()
{
WebRequest webRequest = WebRequest.Create("http://localhost/");
webRequest.ContentType = "application/json";
webRequest.Method = "POST";
TestA ta = new TestA();
string a = JSON.Instance.ToJSON(ta);
byte[] bytes = Encoding.UTF8.GetBytes(a);
Stream os = null;
webRequest.ContentLength = bytes.Length; os = webRequest.GetRequestStream();
os.Write(bytes, 0, bytes.Length);
if (os != null)
{
os.Close();
}
WebResponse webResponse = webRequest.GetResponse();
StreamReader sr = new StreamReader(webResponse.GetResponseStream());
string s = sr.ReadToEnd();
TestB tb = JSON.Instance.ToObject<TestB>(s);
}
and i have a server in php v. 5.3 to response this:
$data = file_get_contents("php://input");
$obj = json_decode($data);
$ret = json_encode($obj->tb);
$len = strlen($ret);
header("Content-length: $len");
echo $ret;
return;
So in the class is return inner value of class TestB (tb). Send is ok, it sends $types, and $type. But in return it send me:
{"$type":"2","b":3,"c":"AA"}
Doesn't send information about types ($types), and in your code the value of globaltypes
is empty because the return information is $types and code will have exception on line:
if (globaltypes.TryGetValue((string)tn, out tname))
tn = tname;
|
|
|
|

|
Hi, I have a exception while parsing a json string which contains numbers formatted as:
Points": [
{
"X": 0.1097,
"Y": 0,
"Z": 4.16366160299608e-18 // <- bug here
}
]
To fix it, in JSONParser.cs (line 308, function ParseNumber()) , replace:
return decimal.Parse(s,NumberFormatInfo.InvariantInfo);
with:
return Double.Parse(s,NumberFormatInfo.InvariantInfo);
Thanks.
Alex.
|
|
|
|

|
First of all, thanks for sharing that little useful library! I just wonder why doesn't it support deserialization of arrays (admittedly, you can use List, but still)? The necessary code changes seem to be trivial.
Regards,
Andrew
|
|
|
|

|
Good tips
|
|
|
|

|
¿It is possible to deserialize immutable classes?
If i have a class like this:
class Immutable
{
public Immutable( long id )
{
this.Id = id;
}
public long Id { get; private set; }
}
with JsonNet i must add a attribute to them and an empty constructor and leave the class like this:
class Immutable
{
[JsonConstructor]
private Immutable() : this(0) { }
public Immutable( long id )
{
this.Id = id;
}
[JsonProperty]
public long Id { get; private set; }
}
Thanks
Iker eL_FRuTeRo
|
|
|
|

|
I am trying to serialize and deserialize a variable of type System.Type. Is that possible? If yes, what am I doing wrong?
System.Type type = typeof(string);
var jsonText = JSON.Instance.ToJSON(type);
var newType = JSON.Instance.ToObject(jsonText) as Type;
I get the following exception:
System.Exception : Failed to fast create instance for type 'System.RuntimeType' from assemebly 'System.RuntimeType, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'
----> System.ArgumentNullException : Value cannot be null.
Parameter name: con
at fastJSON.JSON.FastCreateInstance(Type objtype) in JSON.cs: line 164
at fastJSON.JSON.ParseDictionary(Dictionary`2 d, Dictionary`2 globaltypes, Type type) in JSON.cs: line 471
at fastJSON.JSON.ToObject(String json, Type type) in JSON.cs: line 82
at fastJSON.JSON.ToObject(String json) in JSON.cs: line 75
(I also posted this on CodePlex: [^]. I am not sure where the official forum is.)
|
|
|
|

|
Trying to convert several legacy MVC3 apps to use fastJSON serializer to replace heavy Newtonsoft.Json.JsonConvert.SerializeXmlNode on XMLdocument or Datasets. Our client JavaScript apps require the Ex1 format below for use in jqGrid library. Tried w/ fastJSON (Ex4 & Ex5 output) but can not seem to get the key:value format like Ex1. Is Ex1 serialized output format possible in fastJSON? How? Many thanks for your help!
---------------------------------------------------------------------------
Ex1:Newtonsoft.Json.JsonConvert.SerializeXmlNode
{"person":[{"@id":"1","name":"Alan","url":"http://www.google.com"},{"@id":"2","name":"Louis","url":"http://www.yahoo.com"}]}
---------------------------------------------------------------------------
Ex2:JavaScriptSerializer.Serialize(xmlDoc.InnerXml)
"\u003croot\u003e\u003cperson id=\"1\"\u003e\u003cname\u003eAlan\u003c/name\u003e\u003curl\u003ehttp://www.google.com\u003c/url\u003e\u003c/person\u003e\u003cperson id=\"2\"\u003e\u003cname\u003eLouis\u003c/name\u003e\u003curl\u003ehttp://www.yahoo.com\u003c/url\u003e\u003c/person\u003e\u003c/root\u003e"
---------------------------------------------------------------------------
Ex3:JavaScriptSerializer: DataSetToJSON using dictionary
{"person":[["Alan","http://www.google.com","1"],["Louis","http://www.yahoo.com","2"],null]}
---------------------------------------------------------------------------
Ex4:fastJSON: DataSet to dictionary
{"person":[["Alan","http://www.google.com","1"],["Louis","http://www.yahoo.com","2"],null]}
---------------------------------------------------------------------------
Ex5:fastJSON.JSON.Instance.ToJSON(ds)
{"$schema":{"$type":"fastJSON.DatasetSchema, fastJSON, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null","Info":["person","name","System.String","person","url","System.String","person","id","System.String"],"Name":"root"},"person":[["Alan","http://www.google.com","1"],["Louis","http://www.yahoo.com","2"]]}
---------------------------------------------------------------------------
|
|
|
|

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

|
Hi Mehdi,
under features you list fastJson as being threadsafe. I wonder if the _usingglobals field doesn't break this.
Unless you specify either true or false globally and never change it
through the Parameters, you can end up with the following scenario:
E.g. _usingglobals is set to false per Parameters.
Deserializing a json string which was serialized with global types and extensions will set it to true in ParseDictionary.
Intermittent serialization on another thread sets it back to false.
Ths initial Deserialization hits the "if (found)" on a sub-object (or even on the initial object after a thread yield), tn contains a number (e.g. "2") but _usingglobals is false again.
Therefore it will *not* look up the globaltypes but instead ultimately call Type.GetType("2") which must fail.
Cheers
Phil
|
|
|
|

|
Hi @ all,
i'm a beginner in C# but i have good knowledge of PHP & Phyton.
I have a Program which opens a JSON encoded file and modifies it with File.Append() but i want to edit the JSON as an Array (or something similar), so i can search specific keys and edit the values.
i can load the file:
object jsonText;
file_path = "path_to_file"
jsonText = fastJSON.JsonParser.JsonDecode(File.ReadAllText(file_path));
How can i loop through the key0>values or edit specific values ?
|
|
|
|

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

|
Hello Mr Gholam,
at first... i'm using fastJSON a lot and it is now my standard for serializing/deserializing and storing any sort of data. It is so great, thanks for all that great work!
Now to the (little) problem. If i have a object, which is null (see code below) and want to serialize that, i get an exception.
This is for many people okay, but wouldn't it be better, just to check if the object is null and then to return "null"? Because in my application, it is allowed, that for example that property is null. But that would crash my serialization.
Dictionary<string,string> myDict = null;
fastJSON.JSON.Instance.ToJSON(myDict);
Maybe we could do this with a new JSONParameter?
Is there any way to get this as "standard" in your project? I wouldn't like now to create my own branch, just for this simple piece of code, which would improve a lot of scenarios for all developers out there.
Thank you!
|
|
|
|

|
JSONParameters JSONP = new JSONParameters();
JSONP.UseExtensions = false; JSONP.SerializeNullValues = false;
JSONP.ShowReadOnlyProperties = true;
Response.ContentType = "text/plain";
Response.Write(JSON.Instance.ToJSON(new testcl(), JSONP));
class testcl{
public int cardType;
public bool groupStatus;
public string groupQBId;
}
"cardType":0,"groupStatus":false}
fix:
internal string ConvertToJSON(object obj)
{
WriteValue(obj);
string str = "";
if (_params.UsingGlobalTypes && _globalTypes != null && _globalTypes.Count > 0)
{
StringBuilder sb = _before;
sb.Append("\"$types\":{");
bool pendingSeparator = false;
foreach (var kv in _globalTypes)
{
if (pendingSeparator) sb.Append(',');
pendingSeparator = true;
sb.Append("\"");
sb.Append(kv.Key);
sb.Append("\":\"");
sb.Append(kv.Value);
sb.Append("\"");
}
sb.Append("},");
sb.Append(_output.ToString());
str = sb.ToString();
}
else
str = _before.ToString() + _output.ToString();
return str;
}
|
|
|
|

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

|
I,
At first, it is a wery nice job and article. Thanks.
On version 2.0.3 after have change project settings from silgerlight 4 to silverlight 5, it is no more compile. Here are the errors :
C:\wink\sources\wink-client\trunk\fastJSON\Reflection.cs(83,51): error CS1729: 'System.Reflection.Emit.DynamicMethod' does not contain a constructor that takes 7 arguments
C:\wink\sources\wink-client\trunk\fastJSON\Reflection.cs(114,40): error CS1729: 'System.Reflection.Emit.DynamicMethod' does not contain a constructor that takes 5 arguments
C:\wink\sources\wink-client\trunk\fastJSON\Reflection.cs(195,40): error CS1729: 'System.Reflection.Emit.DynamicMethod' does not contain a constructor that takes 5 arguments
C:\wink\sources\wink-client\trunk\fastJSON\Reflection.cs(231,36): error CS1729: 'System.Reflection.Emit.DynamicMethod' does not contain a constructor that takes 4 arguments
into the msdn doc, DynamicMethod class has these methods but also talk about some restrictions
http://msdn.microsoft.com/en-us/library/system.reflection.emit.dynamicmethod.dynamicmethod(v=vs.95)[^]
This member is security-critical, which restricts its use.
Do you experiment the same things ?
Do you plan to add silverlight 5 support in future ?
|
|
|
|

|
public class FastJsonDataTable
{
public DataTable dt { get; set; }
}
private void btnFastJson_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
FastJsonDataTable fjd = new FastJsonDataTable();
fjd.dt = (DataTable)this.dataGridView1.DataSource;
var jsonText = fastJSON.JSON.Instance.ToJSON(fjd.dt);
this.richTextBox1.Text = jsonText; //<-- OK~! Good View...
dataGridView2.DataSource = fastJSON.JSON.Instance.ToObject<FastJsonDataTable>(jsonText); //<--Never Nothing...
}
|
|
|
|

|
very Good! Mother of many sources =)
|
|
|
|

|
it says it supports silverlight but it doesn't
|
|
|
|

|
I have a class A which has an auto property which references class B:
public class A
{
public class B {get; set;}
}
Parsing fails when reference is set to an instance of class B
Let me know if you are not able to reproduce and I will supply you with my code
|
|
|
|

|
The silverlight project doesn't build because Reflection.cs is not part of the project. I tried to add it but there are other errors too. Format.cs is also not part of the project, and the DynamicMethod constructor has different parameters in silverlight.
Must I try the 1.7 version instead?
|
|
|
|
|
|
|

|
Is there any way to prevent fastJSON from including the fully qualified type names in the $types array? i.e. instead of "MyLib.Customer, MyLib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=..etc.." I just want to see "MyLib.Customer".
|
|
|
|

|
Sounds great. I wanted to something similar but it didn't seem worth the effort for the extra 1000ms here and there. Now I can use yours!
Have a 5!
|
|
|
|

|
fast, well maintained, and well readable source
|
|
|
|

|
Polymorphism is a very useful feature, it simplifies things alot. I have a question, namely, can your library serialize/deserialize object graphs (namely, object references preserving)? I had a feeling that most jason based serialization libs do not preserve object references, am I right? I read your article briefly so if you have already mentioned it in the article, please execuse me, but I still prefer a quick anwser .
Having way too many emails to deal with? Try our SQLized solution: Email Aggregation Manager[ ^] which gets your email sorted, found and organized beyond known precision.
|
|
|
|

|
Should FillObject also preserve fields of embedded classes?
In the following example "Org" field is preserved, but not the Person fields of the embedded object.
public class Profile
{
public class PersonData
{
public string Name;
public string Email;
public string Phone;
}
public string Loc;
public string Org;
public PersonData Person;
}
var p = new Profile();
//...
//fill p with data
//...
// populate p with data from JSON string
p = fastJSON.JSON.Instance.FillObject(p , @"{""Loc"":""CH"",""Person"":{""Email"":""p@host.com""}}");
|
|
|
|

|
Serializing a collection works very nicely, but I'm having a heck of a time getting a string deserialized back into a collection. Here is a sample of the code:
List<TimeEntry> myEntries = new List<TimeEntry>();
for (int x = 0; x < 10; x++)
{
TimeEntry entry = new TimeEntry();
...
myEntries.Add(entry);
}
string jsonText = fastJSON.JSON.Instance.ToJSON(myEntries);
List<TimeEntry> testEntries = new List<TimeEntry>();
var newObject =
(List<TimeEntry>)fastJSON.JSON.Instance.FillObject(myEntries,jsonText);
The code runs, but newObject is null. If I call JSON.Instance.Parse on the string I get an ArrayList of Arrays; workable, but not useful.
|
|
|
|

|
Cool, but don't work correctly.
Need change
private SafeDictionary Getproperties(Type type, string typename)
sd.Add(_params.IgnoreCaseOnDeserialize ? p.Name.ToLower() : p.Name, d);
sd.Add(_params.IgnoreCaseOnDeserialize ? f.Name.ToLower() : f.Name, d);
|
|
|
|

|
The consoletest do not run when i change the target framework from 3.0 to 4.0.
Version 1.9.8 works fine.
|
|
|
|

|
Does fastJSON suport lists at root level since version 1.9.9?
Txs,
Cosma
|
|
|
|

|
How are you calculating your average values?
|
|
|
|

|
wow! Another excellent article! Impressive work Mehdi
|
|
|
|

|
I already voted this code 5 because it is soooo fast! One thing I noticed:
This code:
else if (obj is string || obj is char)
WriteString((string)obj);
will not work on a char type.
Please change to something like:
else if (obj is string || obj is char)
WriteString(obj.ToString());
You can see this in action if you change the sample code to:
var q = new { Name = "asassa", MiddleInitial = 'G', Address = "asadasd", Age = 12 };
Thanks again for sharing this... it really is fast.
|
|
|
|

|
Blazing fast! I have a small array of objects that takes:
27866 ms in JavaScriptConvert.SerializeObject
22667 ms in JavaScriptSerializer.Serialize
and .2058 ms in fastJSON
Yes, that is 100K times faster!
|
|
|
|
|

|
Could you post a small sample code that shows us how to use your fastJSON in a WCF service?
I think I'm not the only one interested in it.
|
|
|
|

|
Hello,
Is fastJSON able to report where a json file is not correctly formated ?
This would be usefull:
- the line number
- the character index
- the error type
Thanks !
|
|
|
|
|

|
Formatter.cs, line 59 says
if (!IsEscaped(output, i))
It should be
if (!IsEscaped(output, output.Length))
because it needs to look for an escaped quote relative to the OUTPUT
buffer, not the INPUT string.
|
|
|
|
 |
|
|
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,565,340 |
| Downloads | 26,031 |
| Bookmarked | 464 times |
|
|