3

I need to parse JSON strings to:

private Dictionary<string, dynamic> dict = new Dictionary<string, dynamic>();

Where the values are restricted numeric arrays (all ints or doubles (or even dicts but not mixed) and other dicts like that one (recursively).

I can use Newtonsoft's ExpandoObjectConverter to parse the dict, but I'm getting arrays as Object[] instead of int[] or double[,]. I'm using my own Serializer which cast the List<object> the ExpandoObjectConverter create to object[].

I do assume more about my information, so how can this be done?

galah92
  • 3,621
  • 2
  • 29
  • 55
  • So like this? https://gist.github.com/FurkanKambay/f0b2a73034895ac188a1a4733f5bb867 – Furkan Kambay Feb 12 '18 at 17:04
  • The `ExpandoObjectConverter` implementation looks like it's creating `List`, not the `object[]` you say you're getting. Are you actually getting a different type, are you actually using another `ExpandoObjectConverter` class, or am I misreading what it does? –  Feb 12 '18 at 17:05
  • @FurkanKambay Exactly. Arrays can be multidimensional, and possible have `dict`s in them (again, all `dict`s without other types). – galah92 Feb 12 '18 at 17:10
  • @hvd I'm using my own version which cast `List` to `object[]` where all the rest is the same. sorry for not mentioning it. – galah92 Feb 12 '18 at 17:11
  • @galah92 If you've already got custom code to convert `List` to `object[]`, modifying that to convert to either `int[]` or `double[]`, depending on which values you've got, seems trivial. If all values are of type `int`, convert to `int[]`. If all values are of type `double`, convert to `double[]`. Otherwise (which you say never happens), throw an exception to signal bad input. Is this the part you're having trouble with, or did this miss some important case? –  Feb 12 '18 at 17:16
  • Technically you're right. I'm having trouble with multidimensional arrays (because I need to parse them recursively in a way) and with the fact that I might be needed to add more types later (besides `int` and `double`), so I'm basically wandering if there's an elegant way of achieving this. Maybe a hack in `Json.Net` I missed that could help. Also, how do I check if they're all of the same type efficiently? – galah92 Feb 12 '18 at 17:24
  • This should be helpful: https://stackoverflow.com/q/18994685/4187549 – Furkan Kambay Feb 12 '18 at 17:28
  • @FurkanKambay Thanks, but it looks like the custom `Converter` is useless there. Just parsing it to `JToken` would be enough. Besides that, in my case I do not have a custom class I can parse into (unlike the example), and I cannot define one as one cannot restrict the `dynamic` values (to my knowledge). – galah92 Feb 12 '18 at 17:43

0 Answers0