✅ Can the NewtonSoft JSON package conditionally create classes when parse?
I have a situation where a field in a class will sometimes have a string, but other times have a class instance. Is there a way to have the JSON serializer wrap the string in something so the field doesn't have to be just
object
? It might work out that the string is just a shorthand way of saying "default all other fields in the class instance."14 Replies
something like what?
Well, examine this:
In the first entry,
some other value
is defaulted to some value.yeah
so you want it to create an instance of a class when its not a string, right?
you can do that
I want to create the class instance even when it is a string.
when is what a string, the field? or the value in the json?
If in the JSON
t
is a string, wrap the string in the class.ok yeah u can do that
look up JsonConverter Attribute
So that array would be as though the following was in the JSON.
https://www.newtonsoft.com/json/help/html/CustomJsonConverter.htm
or the generic version is probably better https://www.newtonsoft.com/json/help/html/CustomJsonConverterGeneric.htm
alternatively
u can define an explicit operator Bar that takes a string
newton can detect it and convert the string into bar
I didn't know if the parser would observe that.
the explicit operator choice looks easier
Well, the operator won't help. The instance in the array needs a parent back to the owner. It also be more like this:
That'd produce the same result as:
Discord
Discord - A New Way to Chat with Friends & Communities
Discord is the easiest way to communicate over voice, video, and text. Chat, hang out, and stay close with your friends and communities.
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.