|
|
Comments and Discussions
|
|
 |

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

|
When checking for the presence of attributes, you'll want to use IsDefined, rather than GetCustomAttributes.
MSDN[^]
It is about 4x times faster than using GetCustomAttributes.
|
|
|
|

|
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.)
|
|
|
|
 |
|
|
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,448 |
| Downloads | 26,033 |
| Bookmarked | 464 times |
|
|