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

后端 未结 5 597
余生分开走
余生分开走 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:32

    Some time ago I had the same problem.

    You'll can use Json.NET, but if you don't have control over the json document (as in: 'it has been serialized by some other framework') you'll need to create a custom JsonConverter like this:

    class MyItemConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return typeof(ItemToSell).IsAssignableFrom(objectType);
        }
    
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            JObject obj = JObject.Load(reader);
            string discriminator = (string)obj["ObjectType"];
    
            ItemToSell item;
            switch (discriminator)
            {
                case "apple":
                    item = new Apple();
                    break;
                case "books":
                    item = new Books();
                    break;
                case "melon":
                    item = new Melon();
                    break;
                default:
                    throw new NotImplementedException();
            }
    
            serializer.Populate(obj.CreateReader(), item);
    
            return item;
    
        }
    
    
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
    
        }
    }
    

    Then you'll need to add it to the converters of the JsonSerializerSettings like so:

    JsonSerializerSettings settings = new JsonSerializerSettings
    {
        TypeNameHandling = TypeNameHandling.Objects,
    
    };
    settings.Converters.Add(new MyItemConverter());
    var items = JsonConvert.DeserializeObject>(response, settings);
    

提交回复
热议问题