Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

serialize/deserialize List<T> to JSON

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. :)

like image 567
Hadesara Avatar asked May 26 '11 22:05

Hadesara


People also ask

Can JSON serialize a list?

Json.NET has excellent support for serializing and deserializing collections of objects. To serialize a collection - a generic list, array, dictionary, or your own custom collection - simply call the serializer with the object you want to get JSON for.

How do you serialize a list in Python?

Use json. dumps() to serialize a list into a JSON object. Use json. dumps(list) to serialize list into a JSON string.

What is serialize and deserialize in JSON?

JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object).

What is Jsonconvert SerializeObject C#?

SerializeObject Method (Object, Type, JsonSerializerSettings) Serializes the specified object to a JSON string using a type, formatting and JsonSerializerSettings. Namespace: Newtonsoft.Json.


1 Answers

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>>();
like image 61
Ben Cull Avatar answered Sep 20 '22 01:09

Ben Cull