This is quite annoying and I only need to run this code ONCE. After that, all will get deleted (it's migration code)
I have a List<string> of JSON strings. They contain various different formats of JSON objects, which can look like this:
{
"id": 123
}
{
"id": "7521b497-abb7-46b8-bddc-177a6fd9f974",
"folderId": 123
}
{
"folderId": 123
}
and so on. I need to get the 123, which can be in the properties id and folderId. If I simply do:
class IdModel {
public int Id { get; set; }
}
//inside a function
var model = JsonConvert.DeserializeObject<IdModel>(json);
it will fail when it gets to the second JSON, because id is a GUID. Instead, it would need to look for FolderId, which means I can do something like this:
class IdModel {
public int Id { get; set; }
}
class FolderIdModel {
public int FolderId { get; set; }
}
//inside a function
int folderId;
try {
var model = JsonConvert.DeserializeObject<FolderIdModel>(json);
folderId = model.FolderId;
} catch {
var model = JsonConvert.DeserializeObject<IdModel>(json);
folderId = model.Id;
}
That would be "fine" for this scenario, but I probably have 10 different JSON objects, that all look different. FolderId > Id, because I always know FolderId is the correct one, unless it has no FolderId, in which case it MIGHT have an Id (should explode if neither FolderId or Id is correct).
My question is: Is there a smart way to deserialize to different models, without looking at the JSON? Remember Id can both be a GUID and an integer, depending on the JSON objects.
I know this is really bad and I'm sorry.