【问题标题】:Deserialize enum wrapper反序列化枚举包装器
【发布时间】: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


    【解决方案1】:
    public int value
    {
        get
        {
            return value;
        }
        set
        {
        }
    }
    

    导致无限递归。你可以试试这个

    public int value { get; set; }
    

    【讨论】:

    • 感谢您的回复,但正如您所见,我做了一些更改。谢谢。
    • @GenericController 似乎您序列化了一个对象(不是数组),但尝试将其反序列化为数组(Recipe[])。没有序列化代码很难说。
    • 您是在说 Web api 中的 Get 代码来格式化响应的数据吗?
    猜你喜欢
    • 2019-05-31
    • 2015-07-26
    • 1970-01-01
    • 2012-09-10
    • 2021-11-30
    • 1970-01-01
    • 2014-08-10
    • 1970-01-01
    相关资源
    最近更新 更多