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

旧时模样 提交于 2019-12-07 06:57:42

问题


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: "Name value", Brand: "Brand value", Year: "Year value", Pictures: ["url1", "url2", "url3"] }

Note that each Car have an pictures array with only url string, instead of all the properties that Picture class have.

I know that Json.NET have the notion of Custom Resolver, but I don't sure exactly how to use it.


回答1:


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; }
}



回答2:


Create a JsonConverter which writes a PictureDisplay object as a string.



来源:https://stackoverflow.com/questions/2315570/json-net-how-to-serialize-a-class-using-custom-resolver

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!