I tell you my situation, I have a json file which I get such that:
string jsonData = System.IO.File.ReadAllText(path);
In this case, as an example, a json can be such that:
[
{
"nombre": "Ivan"
},
{
"nombre": "Francisco"
}
]
either
[{
"edad": 55
}]
either
[
{
"dimensiones": 2500
},{
"dimensiones": 800
},{
"dimensiones": 500
},
]
either
[
{
"esNueva": false
}
]
The problem is that I have to deserialize it but I don't know what class it is going to belong to. As in the example suppose I have these 4 classes:
public class Persona
{
string nombre{ get; set; }
}
public class Animal
{
int edad{ get; set; }
}
public class Ropa
{
bool esNueva { get; set; }
}
public class Foto
{
int dimensiones { get; set; }
}
The idea is that the json is one of those classes but I don't know which one exactly. I've thought about making a class that resolves the string that corresponds to the json, but I don't know how to make a method that can return an object that I know but I'm not sure what it is.
How could I do this method?
If you don't know which class the json belongs to, you could perform the test controlling the error
Serialization Error Handling
then the deserialization would be by trial and error, you deserialize each of the classes and see which one does not fail, then you know that it is that structure that coincides
You try with each class and validate which one could deserialize.
As long as you have a
null
response, it fails and could not deserialize, the setting indicates that it does not throw the exception so you do not have to work with ittry...catch
and you can validate it with itif