关闭

JSON - DataContractJsonSerializer

237人阅读 评论(0) 收藏 举报

// convert JSON <-> CLASS
public static string ToJSON( this object obj )
{
    if ( !IsSerializable(obj) )
    {
        throw new Exception("Target object must be serializable.");
    }
    string json = string.Empty;
    DataContractJsonSerializer ser = new DataContractJsonSerializer(obj.GetType());
    using ( MemoryStream ms = new MemoryStream() )
    {
        ser.WriteObject(ms, obj);
        json = Encoding.Default.GetString(ms.ToArray());
    }
    return json;
}
 

 

public static T FromJSON<T>( this string json )
        {
            using ( MemoryStream ms = new MemoryStream(ASCIIEncoding.Default.GetBytes(json)) )
            {
                DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
                return (T)ser.ReadObject(ms);
            }
        }
 
 
public static bool IsSerializable( this object obj )
{
    MemoryStream ms = null;
    BinaryFormatter bf = null;
    try
    {
        ms = new MemoryStream();
        bf = new BinaryFormatter();
        bf.Serialize(ms, obj);
        return true;
    }
    catch ( System.Runtime.Serialization.SerializationException )
    {
        return false;
    }
    catch ( Exception exc )
    {
        throw exc;
    }
    finally
    {
        ms.Close();
        ms.Dispose();
    }
}
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:65268次
    • 积分:1396
    • 等级:
    • 排名:千里之外
    • 原创:79篇
    • 转载:14篇
    • 译文:0篇
    • 评论:2条
    文章分类
    最新评论