首先 要silverlight支持的对象
silverlight支持list<>我们最好用这个
然后只能用silverlight类库建对象类,在c#其他程序中引用silverlight类库,所有程序是共享的silverlight对象类库,silverlight是无法引用其他程序类库的
附上一个 序列化反序列化代码,在其他程序中反序列化直接 引用silverlight类库中的方法出错,原因不明,所以在其他程序中,再把这个代码写一遍,用来反序列化。
public class FormatSerializableSilverlight
{
#region Serialize
/// <summary>
/// Json序列化
/// </summary>
/// <param name="FormatObject"></param>
/// <returns></returns>
public static String SerializeJson(object FormatObject)
{
Type T = FormatObject.GetType();
//json序列化开始
MemoryStream ms = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(T);
ser.WriteObject(ms, FormatObject);
byte[] json = ms.ToArray();
ms.Close();
string jsonString = Encoding.UTF8.GetString(json, 0, json.Length);//序列化得到的字符串
return jsonString;
}
/// <summary>
/// XML序列化
/// </summary>
/// <param name="FormatObject"></param>
/// <returns></returns>
public static String SerializeXML(object FormatObject)
{
Type T = FormatObject.GetType();
//xml序列化开始
MemoryStream ms = new MemoryStream();
XmlSerializer xml = new XmlSerializer(T);
xml.Serialize(ms, FormatObject);//xml序列化的关键代码
byte[] arr = ms.ToArray();
ms.Close();
string xmlString = Encoding.UTF8.GetString(arr, 0, arr.Length);
ms.Close();
return xmlString;
}
/// <summary>
/// DataContract序列化
/// </summary>
/// <param name="FormatObject"></param>
/// <returns></returns>
public static String SerializeDataContract(object FormatObject)
{
Type T = FormatObject.GetType();
//DataContract方式序列化
MemoryStream ms = new MemoryStream();
DataContractSerializer ser = new DataContractSerializer(T);
ser.WriteObject(ms, FormatObject);
byte[] array = ms.ToArray();
ms.Close();
string DataContractString = Encoding.UTF8.GetString(array, 0, array.Length);
return DataContractString;
}
#endregion
#region Deserialize
/// <summary>
/// Json反序列化好像只能反序列化成Json对象,对象需要自己赋值?
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static JsonValue DeserializeJson(string jsonString)
{
//json字符串解析(相当于反序列化)
JsonValue jsonv = JsonObject.Parse(jsonString);
return jsonv;
//Person pTest = new Person() { Age = int.Parse(jsonv["Age"].ToString()), Name = jsonv["Name"].ToString() };
}
/// <summary>
/// XML反序列化
/// </summary>
/// <param name="xmlString"></param>
/// <returns></returns>
public static Object DeserializeXML<T>(string xmlString)
{
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(xmlString));
XmlSerializer xml = new XmlSerializer(typeof(T));
T O = (T)xml.Deserialize(ms);//xml反序列化的关键代码
ms.Close();
return O;
}
/// <summary>
/// DataContract反序列化
/// </summary>
/// <param name="xmlString"></param>
/// <returns></returns>
public static T DeserializeDataContract<T>(string DataContractString)
{
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(DataContractString));
DataContractSerializer ser = new DataContractSerializer(typeof(T));
T O = (T)ser.ReadObject(ms);
ms.Close();
return O;
}
#endregion
}