How to use FastJson to move from a Json string to a collection of objects

I am using fastJSON and I am having a problem. I cannot take a JSON string and convert it to a collection of objects.

I thought this could handle this, but maybe I'm doing it wrong or misunderstood.

Handles polymorphic collections of objects

Here is an example I made in a C # cmd application (just upload the .cs files and add to the project and copy the following code for testing).

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 always zero.

I use fastJSON because I need something that really has no dependency on .NET libraries, and I use monodroid (and possibly later monotouch), and it is very picky about what you can use and cannot use .

For example, I cannot use the Json.net library (I think there is one for monodroid, but I'm trying to make my code reusable when I make part of the iPhone).

+7
source share
2 answers

You should not use ToObject to deserialize the array. Instead, you should use the Parse method to parse JSON.

When using ToObject you are assuming that you have an instance of an object in JSON that is deserialized (not an array or a scalar value), with Parse , it will handle any type that is serialized in JSON and return the corresponding type.

In this case, calling Parse and passing jsonResult to it will return an ArrayList that contains three instances:

 ArrayList arrayList = fastJSON.JSON.Instance.parse(jsonResult) as ArrayList; 

The problem is that now you have an ArrayList containing multiple Dictionary<string, object> instances that have scalar values ​​(or other Dictionary<string, object> instances, in the case of references) associated with the property name.

I would call it a mistake. I expect the parsing of the array will be correct.

You can change the code for ParseArray to sniff the type when calling array.Add .

This still leaves a problem with ParseNumber (which could potentially be called), returning a string. This may or may not affect you.

I will make all the necessary changes and publish the problem with the problem tracker on the CodePlex project website .

+4
source

Note that with fastJSON 2.x, OP code should work fine (note that the syntax has changed a bit).

 List<Class1> wallets = JSON.ToObject<List<Class1>>(json); 
+4
source

All Articles