我整天都在为此苦苦挣扎,我所做的是使用字典对象并将其序列化,但是我收到一条错误消息“无法序列化字典”,应该阅读整个消息,“无法序列化字典时键不是字符串或对象”这现在对我有用并给了我一个键/值对
我有以下对象
public class Meal {
public int mealId;
public int value;
public Meal(int MealId, int Value) {
mealId = MealId;
value = Value;
} }
public class Crew
{
public Meal[] AllocatedMeals {
get {
return new Meal[]{
new Meal(1085, 2),
new Meal(1086, 1) }; } }
public int AllocatedMealTotal {
get {
return this.AllocatedMeals.Sum(x => x.value); } }
}
然后是下面的代码
Dictionary<string,string> MealsAllocated = crew.AllocatedMeals.ToDictionary(x => x.mealId.ToString(), x => x.value.ToString());
return new JavaScriptSerializer().Serialize(
new {
Allocated = new {
Total = crew.AllocatedMealTotal,
Values = MealsAllocated } )
要得到
"Allocated":{"Total":3,"Values":{"1085":"2","1086":"1"}}