serialize/deserialize List<T> to JSON
Asked Answered
I

1

5

I want to be able to serialize/deserialize a generic list what I so far is this

    public static string ToJson(this object obj, int recursionDepth = 100) 
    {
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        serializer.RecursionLimit = recursionDepth;
        return serializer.Serialize(obj);
    }

    public static List<T> ToListObject<T>(this string obj, int recursionDepth = 100)
    {
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        serializer.RecursionLimit = recursionDepth;
        List<T> returnList = serializer.Deserialize<List<T>>(obj);
        return returnList;
    }

I also tried (List<T>)serializer.DeserializeObject(obj)

With the Deserialize it deserializes wrong (to an empty List<T> object) and with DeserializeObject it throws an error saying 'Could not deserialize the given string into an array of T'. And I wont be able to use the IOStream :( Would really appriciate any insight.

UPDATE: Even the basic serialization/deserialization works, it was just not my day when I posted this. :)

Infidelity answered 26/5, 2011 at 22:35 Comment(6)
Have you looked at this article?Windrow
What is the JSON string that you're trying to deserialize? And what is the type T that you're passing to the ToListObject method?Micronesian
Wont work for me as its using a MemoryStream (reading back from it, so it wont be available over a period of time) and I wont be able to use IOStream.Infidelity
WCarlosfigueira: T is the generic class name, can be any defined classInfidelity
Have you considered creating a JavaScriptConverter?Sickness
If you are looking for another tool for JSON serialization you might want to try [JSON.Net][1]. [1]: james.newtonking.com/pages/json-net.aspxJari
P
10

Try this on for size:

public static T ToObject<T>(this string obj, int recursionDepth = 100)
{
    JavaScriptSerializer serializer = new JavaScriptSerializer();
    serializer.RecursionLimit = recursionDepth;
    return serializer.Deserialize<T>(obj);
}

Then use it like this:

mystring.ToObject<List<MyClass>>();
Parallel answered 27/5, 2011 at 0:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.