0

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?

1

1 Answer 1

1

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 { }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.