关于把List转换成Json出错,百度无果
关于把List转换成Json报错,百度无果。
无法序列化类型“System.Runtime.Serialization.Json.DataContractJsonSerializer”。请考虑将其标以 DataContractAttribute 特性,并将其所有要序列化的成员标以 DataMemberAttribute 特性。如果类型为集合,则请考虑将其标以 CollectionDataContractAttribute 特性。有关其他受支持的类型,请参见 Microsoft .NET Framework 文档。
namespace JsRender
{
public partial class GetDataByJson : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
GetData();
}
public void GetData()
{
List<MyPhotos> Photoslist = GetList();
DataContractJsonSerializer jsonObj = new DataContractJsonSerializer(Photoslist.GetType());
string jsonStr = "";
using (MemoryStream stream = new MemoryStream())
{
jsonObj.WriteObject(stream, jsonObj);
jsonStr = Encoding.UTF8.GetString(stream.ToArray());
}
}
private List<MyPhotos> GetList()
{
List<MyPhotos> list = new List<MyPhotos>();
for (int i = 1; i <= 24; i++)
{
MyPhotos myPhotos = new MyPhotos();
myPhotos.Name = "图片" + i;
myPhotos.ID = i;
myPhotos.Path = "~/Img/" + i + "jpg";
list.Add(myPhotos);
}
return list;
}
}
[DataContract]//序列化
public class MyPhotos
{
[DataMember]
public int ID { get; set; }
[DataMember]
public string Name { get; set; }
[DataMember]
public string Path { get; set; }
}
}
------解决思路----------------------
Refer here:
http://www.cnblogs.com/insus/p/3699057.html
无法序列化类型“System.Runtime.Serialization.Json.DataContractJsonSerializer”。请考虑将其标以 DataContractAttribute 特性,并将其所有要序列化的成员标以 DataMemberAttribute 特性。如果类型为集合,则请考虑将其标以 CollectionDataContractAttribute 特性。有关其他受支持的类型,请参见 Microsoft .NET Framework 文档。
namespace JsRender
{
public partial class GetDataByJson : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
GetData();
}
public void GetData()
{
List<MyPhotos> Photoslist = GetList();
DataContractJsonSerializer jsonObj = new DataContractJsonSerializer(Photoslist.GetType());
string jsonStr = "";
using (MemoryStream stream = new MemoryStream())
{
jsonObj.WriteObject(stream, jsonObj);
jsonStr = Encoding.UTF8.GetString(stream.ToArray());
}
}
private List<MyPhotos> GetList()
{
List<MyPhotos> list = new List<MyPhotos>();
for (int i = 1; i <= 24; i++)
{
MyPhotos myPhotos = new MyPhotos();
myPhotos.Name = "图片" + i;
myPhotos.ID = i;
myPhotos.Path = "~/Img/" + i + "jpg";
list.Add(myPhotos);
}
return list;
}
}
[DataContract]//序列化
public class MyPhotos
{
[DataMember]
public int ID { get; set; }
[DataMember]
public string Name { get; set; }
[DataMember]
public string Path { get; set; }
}
}
------解决思路----------------------
Refer here:
http://www.cnblogs.com/insus/p/3699057.html