serialize/deserialize List<T> to JSON

纵饮孤独 提交于 2019-12-04 12:31:27

问题


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


回答1:


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>>();


来源:https://stackoverflow.com/questions/6145906/serialize-deserialize-listt-to-json

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!