【发布时间】:2012-11-26 14:32:33
【问题描述】:
编辑:对代码进行了更改,以使其在服务器端正常运行。仍然收到错误:
"无法将当前 JSON 对象(例如 {"name":"value"})反序列化为类型 'BareCupboard.Models.RecipeIngredient[]',因为该类型需要 JSON 数组(例如 [1,2,3])正确反序列化。 要修复此错误,请将 JSON 更改为 JSON 数组(例如 [1,2,3])或更改反序列化类型,使其成为普通的 .NET 类型(例如,不是像整数这样的原始类型,而不是像可以从 JSON 对象反序列化的数组或列表。 JsonObjectAttribute 也可以添加到类型中以强制它从 JSON 对象反序列化。 路径‘消息’,第 1 行,位置 11。”
我成功地反序列化了我的服务器端代码,以供客户端用于普通实体框架模型。但是,我为我的枚举创建了一个包装器,以使服务器端交互能够以下拉列表等格式修改数据。
在对枚举进行反序列化时,它会卡在自引用循环中。
对以这种方式创建的对象进行反序列化的正确方法是什么。
public enum ingredientType
{
grams = 1,
kilograms = 2,
millileters = 3,
liters = 4,
pinch = 5,
teaspoon = 6,
tablespoon = 7,
whole = 8,
Cup = 9
}
public class ingredientWrapper
{
private ingredientType _t;
public int value
{
get
{
return (int)_t;
}
set
{
_t = (ingredientType)value;
}
}
public ingredientType EnumValue
{
get
{
return _t;
}
set
{
_t = value;
}
}
public static implicit operator ingredientWrapper(ingredientType i)
{
return new ingredientWrapper { EnumValue = i };
}
public static implicit operator ingredientType(ingredientWrapper iw)
{
return iw.EnumValue;
}
它在客户端被反序列化和消费:
public async Task<IEnumerable<Recipe>> GetAll()
{
HttpResponseMessage response = await _Recipeclient.GetAsync(RecipeServiceUrl);
var jsonString = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<Recipe[]>(jsonString);
}
【问题讨论】:
标签: .net json entity-framework asp.net-mvc-4