Deserialize json based on fields in .Net (C#)

后端 未结 5 601
余生分开走
余生分开走 2021-02-09 12:05

I\'m writing an app that gets a Json list of objects like this:

[
   {
       \"ObjectType\": \"apple\",
       \"ObjectSize\": 35,
       \"ObjectC         


        
5条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-09 12:46

    You can use a CustomCreationConverter. This lets you hook into the deserialization process.

    public abstract class Base
    {
        public string Type { get; set; }
    }
    
    class Foo : Base
    {
        public string FooProperty { get; set; }
    }
    
    class Bar : Base
    {
        public string BarProperty { get; set; }
    }
    
    class CustomSerializableConverter : CustomCreationConverter
    {
        public override Base Create(Type objectType)
        {
            throw new NotImplementedException();
        }
    
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var jObject = JObject.Load(reader);
    
            var type = (string)jObject.Property("Type");
            Base target;
            switch (type)
            {
                case "Foo":
                    target = new Foo();
                    break;
                case "Bar":
                    target = new Bar();
                    break;
                default:
                    throw new InvalidOperationException();
            }
            serializer.Populate(jObject.CreateReader(), target);
            return target;
        }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            var json = "[{Type:\"Foo\",FooProperty:\"A\"},{Type:\"Bar\",BarProperty:\"B\"}]";
            List bases = JsonConvert.DeserializeObject>(json, new CustomSerializableConverter());
        }
    }
    

提交回复
热议问题