日期:2014-05-17  浏览次数:20468 次

Json转化为.cs类
由于经常需要调用接口,所以每次都需要手动把XML或Json格式的字符串生成一个.cs模型层文件
个人感觉很麻烦,所以就自己写了个XML转换.CS类的方法
可是Json俺就不会了,XMl可以先转换为XmlNode对象 这样就帮我解决了层次的问题,可是Json目前没找到类似的方法所以
目前无法实现


请问大家有什么好方法可以分享下吗,暂时我是Json转换成XML然后再调用自己的XML转换方法

------解决方案--------------------
public class SerializableHelper
{
/// <summary>
/// 序列化成一个字节数组
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <returns></returns>
public static byte[] SerializeToBytes<T>(T t)
{
MemoryStream mStream = new MemoryStream();
BinaryFormatter ser = new BinaryFormatter();
ser.Serialize(mStream, t);
return mStream.ToArray();
}

/// <summary>
/// 序列化成一个字符串
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <returns>序列化代码</returns>
public static string SerializeToXml<T>(T t)
{
try
{
XmlSerializer s = new XmlSerializer(typeof(T));
Stream stream = new MemoryStream();
s.Serialize(stream, t);

stream.Seek(0, SeekOrigin.Begin); //这一点非常重要 否则无法读取
string strSource = "";
using (StreamReader reader = new StreamReader(stream))
{
strSource = reader.ReadToEnd();
}
return strSource;
}
catch { return null; }

}


public static string SerializeToJson<T>(T t)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(t.GetType());
//DataContractSerializer serializer2 = new DataContractSerializer(typeof(T), typeof(T).Name, string.Empty, null, int.MaxValue, false, true, null, null);

MemoryStream stream = new MemoryStream();
serializer.WriteObject(stream, t);
byte[] dataBytes = new byte[stream.Length];
stream.Position = 0;
stream.Read(dataBytes, 0, (int)stream.Length);
return Encoding.UTF8.GetString(dataBytes);
}



/// <summary>
/// xml 文件反序列化为泛型数组
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="path"></param>
/// <returns></returns>
public static T DeSerialize<T>(FileInfo fi)
{
if (fi.Exists == false) return default(T);

XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));

FileStream fs = fi.OpenRead();
T t;
try
{
t = (T)xmlSerializer.Deserialize(fs);
}
finally
{
fs.Close();
}
return t;
}
/// <summary>
/// 字符串反序列化成一个类
/// </summary>
/// <param name="binary"></param>
/// <returns></returns>
public static T DeSerialize<T>(string stringSource)

if (string.IsNullOrEmpty(stringSource)) return default(T);

try

XmlSerializer x = new XmlSerializer(typeof(T));

Stream st