Home > Enterprise >  C# Newtonsoft.JSON serialize/deserialize array of objects
C# Newtonsoft.JSON serialize/deserialize array of objects

Time:03-09

I'm unsure how to go about serializing/deserializing an array of objects which implement an interface using Newtonsoft.JSON. Here's a basic example:

public interface IAnimal {
  public int NumLegs { get; set; }
  //etc..
}

public class Cat : IAnimal {...}
public class Dog : IAnimal {...}
public class Rabbit : IAnimal {...}

public IAnimal[] Animals = new IAnimal[3] {
  new Cat(),
  new Dog(),
  new Rabbit()
}

How would I go about serializing/deserializing the Animals array?

CodePudding user response:

try this

IAnimal[] animals = new IAnimal[] {
                    new Cat{CatName="Tom"},
                    new Dog{DogName="Scoopy"},
                    new Rabbit{RabitName="Honey"}
    };

    var jsonSerializerSettings = new JsonSerializerSettings()
    {
        TypeNameHandling = TypeNameHandling.All
    };
    var json = JsonConvert.SerializeObject(animals, jsonSerializerSettings);
    
List<IAnimal> animalsBack = ((JArray)JsonConvert.DeserializeObject(json))
.Select(o => (IAnimal)JsonConvert.DeserializeObject(o.ToString(), 
Type.GetType((string)o["$type"]))).ToList();

Test

json = JsonConvert.SerializeObject(animalsBack, Newtonsoft.Json.Formatting.Indented);

test result

[
  {
    "CatName": "Tom"
  },
  {
    "DogName": "Scoopy"
  },
  {
    "RabitName": "Honey"
  }
]

classes

public class Cat : IAnimal { public string CatName { get; set; } }
public class Dog : IAnimal { public string DogName { get; set; } }
public class Rabbit : IAnimal { public string RabitName { get; set; } }

public interface IAnimal { }
  • Related