Ask Your Question
4

Can JSON be used to (de)serialize a type with interface-based polymorphic properties?

asked 2022-12-31 11:00:00 +0000

nofretete gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-08-20 03:00:00 +0000

plato gravatar image

Yes, JSON can be used to serialize and deserialize a type with interface-based polymorphic properties. However, when working with interfaces, it is important to use a serializer that supports interface handling, as not all serializers do.

In languages such as C#, some popular JSON libraries like Newtonsoft.Json and System.Text.Json support interface-based polymorphism. These libraries provide the ability to configure the serialization and deserialization process to handle interfaces appropriately.

For example, consider a class hierarchy using interfaces:

public interface IAnimal {
    string Name { get; set; }
}

public class Dog : IAnimal {
    public string Name { get; set; }
    public bool IsBarking { get; set; }
}

public class Cat : IAnimal {
    public string Name { get; set; }
    public bool IsPurring { get; set; }
}

public class PetOwner {
    public string Name { get; set; }
    public List<IAnimal> Pets { get; set; }
}

To serialize and deserialize this type using JSON, you can use a JSON serializer that supports interfaces. Here is an example using Newtonsoft.Json:

PetOwner owner = new PetOwner {
    Name = "John",
    Pets = new List<IAnimal> {
        new Dog { Name = "Buddy", IsBarking = true },
        new Cat { Name = "Princess", IsPurring = true }
    }
};

string json = JsonConvert.SerializeObject(owner);
PetOwner deserializedOwner = JsonConvert.DeserializeObject<PetOwner>(json);

This serializes the PetOwner object to JSON and then deserializes it back into a new PetOwner object. The interface-based polymorphic properties are handled correctly by the serializer, allowing the object to be fully reconstructed from the JSON representation.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-12-31 11:00:00 +0000

Seen: 57 times

Last updated: Aug 20 '22