目前,我正在使用JsonResults将我的对象从服务器端发送到客户端。
目前的代码如下:
[HttpGet]
public JsonResult Get()
{
//Create a List object, categoryList which can store anonymous objects later.
List<object> categoryList = new List<object>();
var categoriesQueryResult = Database.Categories
.Where(eachCategory => eachCategory.DeletedAt == null)
.Include(eachCategory => eachCategory.CreatedBy)
.Include(eachCategory => eachCategory.UpdatedBy);
//Loop through each Category entity in the categoriesQueryResult's and add it into categoryList
foreach (var oneCategory in categoriesQueryResult)
{
categoryList.Add(new
{
categoryId = oneCategory.CategoryId,
categoryName = oneCategory.CategoryName,
visibility = oneCategory.Visibility,
displayStart = oneCategory.DisplayStart,
displayEnd = oneCategory.DisplayEnd,
createdAt = oneCategory.CreatedAt,
updatedAt = oneCategory.UpdatedAt,
createdBy = oneCategory.CreatedBy.FullName,
updatedBy = oneCategory.UpdatedBy.FullName,
isSpecial = oneCategory.IsSpecial
});
}//end of foreach
return new JsonResult(categoryList);
}// end of get
所以我现在要做的是将List转换为ByteArray,然后将转换后的对象作为ByteArray返回给客户端。
我试过了:
[HttpGet]
public byte[] Get()
{
//Create a List object, categoryList which can store anonymous objects later.
List<object> categoryList = new List<object>();
var categoriesQueryResult = Database.Categories
.Where(eachCategory => eachCategory.DeletedAt == null)
.Include(eachCategory => eachCategory.CreatedBy)
.Include(eachCategory => eachCategory.UpdatedBy);
//Loop through each Category entity in the categoriesQueryResult's and add it into categoryList
foreach (var oneCategory in categoriesQueryResult)
{
categoryList.Add(new
{
categoryId = oneCategory.CategoryId,
categoryName = oneCategory.CategoryName,
visibility = oneCategory.Visibility,
displayStart = oneCategory.DisplayStart,
displayEnd = oneCategory.DisplayEnd,
createdAt = oneCategory.CreatedAt,
updatedAt = oneCategory.UpdatedAt,
createdBy = oneCategory.CreatedBy.FullName,
updatedBy = oneCategory.UpdatedBy.FullName,
isSpecial = oneCategory.IsSpecial
});
}//end of foreach
byte[] convertedObject = categoryList.OfType<byte>().ToArray();
return convertedObject;
}// end of get
但它似乎不起作用。任何回复或帮助将不胜感激。提前谢谢。
答案 0 :(得分:2)
您可以使用BinaryFormatter获取字节数组。
byte[] bytes = null;
BinaryFormatter bf = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream())
{
bf.Serialize(ms, categoryList);
bytes = ms.ToArray();
}