【问题标题】:Trying serialize to json only the base class [duplicate]尝试仅将基类序列化为 json [重复]
【发布时间】:2019-08-14 18:56:44
【问题描述】:

我正在尝试将以下数据保存在 Json 表单中。为此,我正在使用 Newtonsoft.Json 库。有时我只需要序列化 ​​Recipe 对象的 RecipeShort 属性。

    [JsonObject(MemberSerialization.OptIn)]
    public class RecipeShort
    {
        [JsonProperty]
        public string Id { get; set; }

        [JsonProperty]
        public string Title { get; set; }
    }

    [JsonObject(MemberSerialization.OptIn)]
    public class Recipe : RecipeShort
    {
        [JsonProperty]
        private List<Ingredient> ingredients;

        [JsonProperty]
        public string Method { get; set; }
    }

            Recipe res = new Recipe
            {
                Id = "123",
                Title = "Text",
                Method ="Text",
                Ingredients = ingredients
            };

我尝试了几种方法,但都不起作用。

一种方式:

string str1 = Newtonsoft.Json.JsonConvert.SerializeObject(res, typeof(RecipeShort),null);

其他方式:

RecipeShort temp = (RecipeShort) res;
string str1 = Newtonsoft.Json.JsonConvert.SerializeObject((RecipeShort)temp, typeof(RecipeShort),null);

第三种方式:

string str = Newtonsoft.Json.JsonConvert.SerializeObject(res);
RecipeShort temp1 = Newtonsoft.Json.JsonConvert.DeserializeObject<RecipeShort>(str);
string str1 = Newtonsoft.Json.JsonConvert.SerializeObject(temp1, typeof(RecipeShort),null);

前两种方式是完全序列化对象。第三个尝试使用 NullPointerExeption 反序列化失败。

有没有什么优雅的方法可以只序列化基类而不需要手动操作?

【问题讨论】:

标签: c# json serialization polymorphism


【解决方案1】:

您或许可以使用 IContractResolver,请参阅 https://www.newtonsoft.com/json/help/html/ConditionalProperties.htm

【讨论】:

    猜你喜欢
    • 2017-01-20
    • 2015-11-10
    • 1970-01-01
    • 1970-01-01
    • 2017-02-21
    • 1970-01-01
    • 2012-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多