I am trying to save the following data in the Json form. I am using the Newtonsoft.Json library for that. Sometimes I need to serialize only the RecipeShort properties of the Recipe object.
[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
};
I've tried several ways but it did not work.
One way:
string str1 = Newtonsoft.Json.JsonConvert.SerializeObject(res, typeof(RecipeShort),null);
Other way:
RecipeShort temp = (RecipeShort) res;
string str1 = Newtonsoft.Json.JsonConvert.SerializeObject((RecipeShort)temp, typeof(RecipeShort),null);
The third way:
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);
First two ways are fully serialize the object. The third fails on attempt to deserialize with NullPointerExeption.
Is there any elegant way to serialize only the base class without doing it manually?