I am using fastJSON and I ran into a problem. 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.
I am using fastJSON because I need something that really has no dependencies on .NET libraries and I am using monodroid (and probably later monotouch) and it is very picky in what you can use and can’t use.
For instance I can not use the Json.net library (I think there is one for monodroid but I trying to make my code reusable for when I do the iPhone part).
You shouldn’t use
ToObjectto deserialize an array. Instead, you should use theParsemethod to parse the JSON.When using
ToObject, you are assuming that you have an instance of an object in JSON that is being deserialized (not an array, or a scalar value), withParse, it will handle any type that is serialized into JSON and return the appropriate type.In this case, calling
Parseand passingjsonResultto it will return anArrayListwhich contains the three instances:The problem with that is that now you have an
ArrayListcontaining a number ofDictionary<string, object>instances which have the the scalar values (or otherDictionary<string, object>instances, in the case of references) mapped to the property name.I’d classify this as a bug. I’d expect the parsing of an array to handle this correctly.
You could modify the code for
ParseArrayto sniff the type when the call toarray.Addis made.That still leaves an issue with
ParseNumber(which could potentially be called) returning a string. This might or might not impact you.I’d make whatever changes you need as well as file an issue with the issue tracker on the CodePlex project site.