I have a class A
that has a field string data
.
I perform a server request that gets me a json text that I convert to A
:
var a = JsonConvert.DeserializeObject<A>(jsonResponse);
The problem is sometimes data
comes as a string (e.g: Ball
) and sometimes it comes as a json object, like this:
"data" : {
"field1" : "Ball",
"field2" : "Foo"
}
And this breaks the deserialization, since the field data
was expecting a string.
Is there a way to capture data
from the json text as a string even if it comes as a json object?
2
Answers
How about something like this as a starting point? (inspired by .NET TryParse methods):
Then you can use it like:
You can deserialize your
json
intodynamic object
instead of concrete classHow about declaring two separate
DTO
classes, when it isstring
deserialize toB
, if it isjson
object deserialize toA
fiddle here https://dotnetfiddle.net/EJkdMW