1

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?

Tanya
  • 109
  • 1
  • 13
  • 1
    You can use `UpcastingContractResolver` from [this answer](https://stackoverflow.com/a/56468144/3744182) to [How to exclude properties from JsonConvert.PopulateObject that don't exist in some base type or interface?](https://stackoverflow.com/q/56467203/3744182). Demo: https://dotnetfiddle.net/0PcMVQ – dbc Aug 14 '19 at 20:10
  • 1
    `JsonConvert.SerializeObject(res, typeof(RecipeShort),null)` is useful when you want to add a `$type` property to the root. See [Serializing an interface/abstract object using NewtonSoft.JSON](https://stackoverflow.com/a/28133806/3744182). – dbc Aug 14 '19 at 20:23
  • Thanks a lot! Now I've understand better! – Tanya Aug 16 '19 at 13:52

1 Answers1

0

You can probably use IContractResolver, see https://www.newtonsoft.com/json/help/html/ConditionalProperties.htm.

Andrey Sidorenko
  • 180
  • 1
  • 1
  • 11