Json.NET - How to serialize a class using a custom recognizer

I want to serialize this class:

public class CarDisplay
{
    public string Name { get; set; }
    public string Brand { get; set; }
    public string Year { get; set; }

    public PictureDisplay[] Pictures { get; set; }
} 

public class PictureDisplay
{
    public int Id { get; set; }
    public string SecretKey { get; set; }
    public string AltText { get; set; }
}

To this Json test:

{Name: "Value of the Name", Brand: "Trademark", Year: "Value of the Year", Pictures: ["url1", "url2", "url3"]}

Please note that each car has an array of images with only a url string, and not all properties that the Picture class has.

I know that Json.NET has the concept of Custom Resolver, but I don’t know exactly how to use it.

+5
source share
2 answers
public class PictureDisplayConverter : JsonConverter
{
   public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
   {
        // convert array of picture to json string;
   }

   public override object ReadJson(JsonReader reader, Type objectType, JsonSerializer serializer)
   {
       // convert back json string into array of picture
   }

   public override bool CanConvert(Type objectType)
   {
        return true;
   }
}

In your car display class:

public class CarDisplay
{
    public string Name { get; set; }
    public string Brand { get; set; }
    public string Year { get; set; }

    [JsonConverter(typeof(PictureDisplayConverter ))]
    public PictureDisplay[] Pictures { get; set; }
}
+10
source

JsonConverter, PictureDisplay .

0

All Articles