0

I recently had to parse JSON data like

[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]

like this:

 var reqData = JsonConvert.DeserializeObject<Dictionary<string, object>>("{" + fileData + "}");

which I used in another project where the data was well formattted. Here, however, the data was somewhat corrupt. For instance "firstName" might appear as ".\"firstName" and so forth. Using JSON like above results in an exception thrown.

I tried various schemes to "purify" the data but as I cannot predict the state of other data, I stopped using JSON and just parsed it myself (with heavy use of substrings and counting to isolate the keys and values). That method works OK but of course using JSON would be much simplier.

Is there a way around this with JSON?

Ron
  • 2,435
  • 3
  • 25
  • 34
  • 2
    Why is the JSON you're getting corrupt? Do you have control over the JSON source? If so, you should look into why you're getting corrupt data, instead of how to work around it – Jedediah Aug 05 '15 at 14:40
  • I have no control over the source. – Ron Aug 05 '15 at 17:08

1 Answers1

1

The main Problem is to define corrupt data. If you know that there is never a substring .\" so you can replace it with an empty string and parse it afterwards. That is no problem, but it can be dificult to do something like this if it is more complex.
It is sometimes no problem for an human to read corrupt data withut a valid format - but it is almost impossible for simple algorithms.

By the way, the formatting ".\"firstName" is a valid JSON element because the " is escaped by \. See this question too.

Community
  • 1
  • 1
Koopakiller
  • 2,838
  • 3
  • 32
  • 47
  • Yes, the \" is ok but the "." was not. This was in one file and I figure, what's next? By using positional code (searching for delimiters, etc.) I does not fail. But i just wondered if there was a way to use JSON in a "more forgiving" fashion. Guess not. THANKS!!! – Ron Aug 05 '15 at 15:08