【问题标题】:Deserialization of get only properties in C# using json.net / webapi [duplicate]使用 json.net / webapi 在 C# 中反序列化仅获取属性 [重复]
【发布时间】:2012-10-13 20:49:45
【问题描述】:

可能重复:
Using Json.net - partial custom serialization of a c# object

我有一个类,当使用 asp.net MVC 4 WebAPI 时,我成功地在 json.net 中序列化。该类有一个属性是字符串列表。

public class FruitBasket {
    [DataMember]
    public List<string> FruitList { get; set; }

    public int FruitCount {
        get {
            return FruitList.Count();
        }
    }
}

在我的 Get 方法中,序列化正常,我得到一个空数组,即 JSON 中 FruitList 属性的 []。如果我在 PUT 请求的正文中使用相同的 json,我会在反序列化期间在 FruitCount 属性中收到错误,因为 FruitList 为空。

我希望 FruitList 属性(基本上是我的 get only 属性)序列化但不反序列化。是否可以通过 json.net 进行设置或其他方式?

【问题讨论】:

  • 只是一个简单的问题.. 您知道序列化是扁平化代码/对象层次结构的过程吗?从这个角度来看,你不能真正序列化一个属性,因为它只是一个方法。您是否对属性后面的字段进行了序列化,还是我没有正确理解这个问题?

标签: c# asp.net-mvc-4 asp.net-web-api json.net


【解决方案1】:

我知道这并不能回答您的问题,但可以解决正在生成的错误,因此可能无需担心自定义序列化

为 FruitList 使用私有变量,在 get 和 set 中返回,如果值为 null 则将私有变量设置为新列表。

public class FruitBasket
{
    private List<string> _fruitList;

    [DataMember]
    public List<string> FruitList
    {
        get
        {
            return _fruitList;
        }
        set
        {
            if (value == null)
            {
                _fruitList = new List<string>();
            }
            else
            {
                _fruitList = value;
            }
        }
    }

    public int FruitCount
    {
        get
        {
            return FruitList.Count();
        }
    }
} 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-08
    • 1970-01-01
    • 2012-05-20
    • 2016-05-31
    • 2023-03-24
    • 1970-01-01
    相关资源
    最近更新 更多