0

The json token.ToObject<T> method can throw if json is not able to convert the data in token the to the type T.

I would like to do a early test and need a method like this:

bool JsonConvert.CanConvert<TSrc, TDest>();

I don't find any reference to something close to it.

[Precision]

Actually TSrc here is not composed but a basic type.

[Edit]

When I say that I want to do an early test, I talk about a test done before any attempt to parse somethings.

Actually I don't have any json file around when I need to do the test.

So the TryParse or the TryCatch pattern doesn't match my need.

Community
  • 1
  • 1
Orace
  • 7,822
  • 30
  • 45
  • 5
    There's only one way to know if it will parse to a given type: parse it. –  Nov 28 '16 at 14:30
  • 1
    That likely doesn't exist because the idea is that if the json isn't what you expect then you're in an exceptional or error case. – juharr Nov 28 '16 at 14:36

1 Answers1

3

Why an early test? Just enclose the call with a try-catch. What you're suggesting would internally parse the string as well, so speed-wise it would make no difference. Better yet, it will be parsed only once. If it succeeds, fine. If not, you'll know too.

Frank
  • 431
  • 1
  • 5
  • 25
  • `Why an early test?`... because I actually need it ... I want my generic code to throw on construction, not in parsing. – Orace Nov 28 '16 at 15:55
  • "What you're suggesting would internally parse the string as well, so speed-wise it would make no difference." You can't actually know if it will parse into a structure unless you attempt it. There is no shortcut. –  Nov 28 '16 at 21:03