I have some JSON here. The problem is it doesn't match the classes data types anymore. My question is; is it possible to deserialize JSON Dynamically? i.e. if I have entirely different JSON's can I deserialize them into two entirely different classes without first knowing what class I want to deserialize each into.
Asked
Active
Viewed 673 times
2
-
1Are the 2 types a subset of each other? – TheGeneral Apr 09 '18 at 11:48
-
What do you mean by "adding another JSON type"? You mean adding another field? – Anastasios Selmani Apr 09 '18 at 11:49
-
For example .The first json type is like the one in the top. And the second one is totally different JSON type with different fields. – Angelo Sanchez Apr 09 '18 at 11:51
-
So two entirely different JSON's which would serialize into two entirely different classes? You say dynamically so do you not know what you want to serialize it into? – d219 Apr 09 '18 at 11:59
-
1Exactly. Is that possible? – Angelo Sanchez Apr 09 '18 at 12:01
-
1Possible duplicate of [Deserialize JSON into C# dynamic object?](https://stackoverflow.com/questions/3142495/deserialize-json-into-c-sharp-dynamic-object) – Anastasios Selmani Apr 09 '18 at 13:14
-
Franctly if you just google your title or search in SO you will find the answer to your question immediately. https://stackoverflow.com/questions/3142495/deserialize-json-into-c-sharp-dynamic-object – Anastasios Selmani Apr 09 '18 at 13:15
1 Answers
8
You can deserialize dynamic object with using newtonsoft
like bellowing code piece.
dynamic dynamicObj = JsonConvert.DeserializeObject(jsonStr);
string name = dynamicObj.data.code;
But in my personal preference is using strong type. I think its more convenience.
you can use quictype for generating c# classes from JSON object
quicktype generates strongly-typed models and serializers from JSON, JSON Schema, and GraphQL queries, making it a breeze to work with JSON type-safely in any programming language.
Hope the answer helps to you.

arslanaybars
- 1,813
- 2
- 24
- 29