skip to Main Content

I’m new to using json serialization in C#.

[Redefined question]

I have a class of classes, Brains. Each nested class will inherit from IBrain interface, but not necessarily are limited to it’s fields.
I am selecting a type at runtime using typeof(Brains).GetNestedTypes().Where(brain => brain.GetInterface("IBrain") != null).ToArray(); and selecting an index in that array as the type to use.

Is there a way I can save an instance of that type to a json, and load an instance of that type from a json. If there is a different way I should be trying to solve this problem (e.g. without json), please let me know. (should I just define individual load and save functions within each nested class?)

2

Answers


  1. Chosen as BEST ANSWER

    It seems that it wasn't reading in the fields, it required them to be properties. I am now looking for this feature in the documentation.


  2. To serialize/deserialize derived types there is Polymorphis serialization, that adds type information that can be used to deserialize to the correct type. Note that you would typically still need to know about all derived types at compile time.

    Serializing a object with a type only known at runtime should also work fine. The serialize method just takes an object and a Type. And the Type can be created from the object itself.

    Deserializing a completely unknown type will however be more challenging. You could still pass a Type-object, but that require you to somehow know what type it should be. But without any static type you cannot really use the object for anything, at least not without using reflection or dynamic, and neither is something I would recommend. So you would probably need to treat the json as a tree of properties, See Json Document Object Model.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search