序列化/反序列化列表< T>以JSON [英] serialize/deserialize List<T> to JSON

查看:232
本文介绍了序列化/反序列化列表< T>以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;
    }



我也试过(列表< T>)串行器.DeserializeObject(OBJ)

随着反序列化它反序列化错误的(为空列表< T> )对象和 DeserializeObject ,它抛出一个错误,说'给定的字符串无法反序列化到一个数组的T'。而且我不会是能够使用的iostream :(真的会appriciate任何见解。

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

推荐答案

试试这个关于大小:

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

这篇关于序列化/反序列化列表&LT; T&GT;以JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆