【发布时间】: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 反序列化失败。
有没有什么优雅的方法可以只序列化基类而不需要手动操作?
【问题讨论】:
-
您可以使用从this answer 到How to exclude properties from JsonConvert.PopulateObject that don't exist in some base type or interface? 的
UpcastingContractResolver<Recipe, RecipeShort>。演示:dotnetfiddle.net/0PcMVQ -
JsonConvert.SerializeObject(res, typeof(RecipeShort),null)在您想将$type属性添加到根时很有用。见Serializing an interface/abstract object using NewtonSoft.JSON。 -
非常感谢!现在我明白了!
标签: c# json serialization polymorphism