❔ Parsing JSON value with multiple different possibilities
I have a JSON object which can take on one of two different structures
How would I go about parsing this into an object using STJ? Assume the object to deserialize to is this
20 Replies
You'd want a converter, i assume
Yeah, guess I should probably invesitgate how to properly write one
hmm
Luke, use generics!
idk how generics would help in this situation
If the object
name
contains first
and last
fields return a Person
class; otherwise return a full string (and split them as ero did). Use generics just like Johnny mentioned.yeah I've done that and it works
however I don't get what you mean by "use generics"
Generic classes and methods
Learn about generics. Generic types maximize code reuse, type safety, and performance, and are commonly used to create collection classes.
An important concept in deserialisation
yes I know what generics are
So?
Use
JsonConvert.DeserializeObject<GENERIC_T>
to get the return type you want. That's the idea.yes? of course, albeit using STJ
The question wasn't about how to deserialize JSON, it was about how I'd create a converter for this specific scenario
Ah I see
I assume it's indeed easiest to navigate the JSON with a JsonDocument first and then Deserializing it to your respective type as soon as traversing the JSON got you enough information to figure out what the type is
Probably the other alternative would be to do a greedy try-catch wrapped deserialize to both types
In case the first one is not compatible it would just throw
Or it'd just return null?
I'm not sure on the spot right now whether it threw or returned null in case the json didn't match the type, I think it throws but would have to check
Same
But I guess other than that, a custom converter would probably not help much since the "converting" part is already covered, your types match the JSON, so there's no need to teach STJ how to parse them
Unless you're actually asking how to potentially get both JSON shapes into a single internal type for a Name
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.