Refactoring objects issue
So a long long time ago i implemented Objects and how they are set in a very stupid way, which i am now correcting by adapting them to be compatible with the default JSON Serializer and bringing the code to overall more structure by following C# conventions more
My issue
I want to structure the following object (shown in the screenshot) to use [JsonPropertyName] and such instead of the constructor with a JObject (from Newtonsoft JSON), which would be no problem, however, as you can see some values use a different key (for example ndcId is in "o":{"ndcId":0000}) while others are more nested (like "o":{"chatmessage":{"content"}})
What would be the proper approach to serialize them with the default serializer while keeping them in the same class as i dont want to split up my class for every branch of "o"
18 Replies
You would turn it into a two-step process. Deserialize to a model that matches the JSON (several records), then map to a model with a flat structure the way you want it
Do you have any examples of that? I don't quite understand
Make classes that one-to-one reflect the JSON structure
Deserialize to that
But isn't that just creating like 3 classes for one object?
Then, make a mapping method/constructor like above, that turns that nested structure into a flat structure as you want
{ means object in json
Yes
You have more than one object here
:SCcrying:
Is there any other way.
Any other way would be a hack
¯\_(ツ)_/¯
What if I just deserialize it into an object from "o"/"chatMessage"
I don't understand
Like
Instead of passing the whole JSON, I make the root point "o"/"chatMessage" so it can deserialize from there
Sure
Would that also be a hack.
Not really?
I really don't need the _type value it's more used in the socket that checks the value
So I can safely skip it
If you change the JSON structure, your deserializarion types reflect that change
But how would you extract the o/chatMessage without deserializing the JSON?
Anyways, gonna sleep. Nn
There's some way to get JSON from a specific JSON key in the default serializer
Good night