1

I am currently getting invlaid JSON back from TFS similar to the following:

{
  "value": [
    {
      "version": 46874,
      "changeDate": "2016-10-27T11:18:37.14Z",
      "size"/8,
      "hashValue": "ADnOi7g3m13IlYXnt9Q5Qw==",
      "path": "$/some/random/file",
      "url": "https://example.com/blah"
    }, //...
  ],
  "count": 14
}

While the TFS admins figure out what is wrong with TFS, I've decided that the, while undesirable, not having the file's size is not crucial to the project and I want to just ignore this error for now.

Google lead me to this question. If I wanted to ignore all errors, this would be fine. I only want to ignore the error for the size property. So I wrote this error handler:

    public void HandleDeserializationError(object sender, Newtonsoft.Json.Serialization.ErrorEventArgs errorArgs)
    {
        if (errorArgs.ErrorContext.Path.EndsWith(".size"))
            errorArgs.ErrorContext.Handled = true;
    }

Unfortunately, errorArgs.ErrorContext.Path is value[2].changeDate when parsing the line "size"\8,. This seems wrong.

I could store the response in a field before deserialization and then use errorArgs.ErrorContext.Error.LinePosition like so:

    public void HandleDeserializationError(object sender, Newtonsoft.Json.Serialization.ErrorEventArgs errorArgs)
    {
        var pos = (errorArgs.ErrorContext.Error as JsonReaderException)?.LinePosition ?? 0;

        if (pos > 6 && _parseData.Substring(pos - 6,6) == "\"size\"")
            errorArgs.ErrorContext.Handled = true;
    }

This seems awkward though. Does anyone have a better suggestion?

Community
  • 1
  • 1
mrfelis
  • 736
  • 7
  • 18
  • Json.NET allows you to ignore and continue from deserialization errors. It doesn't always allow you to continue from *file parsing* errors because the error itself may leave the parser in a confused state, not knowing how to continue tokenizing the JSON stream. That may be happening here. You may need to fork and customize [`JsonTextReader`](https://github.com/JamesNK/Newtonsoft.Json/blob/master/Src/Newtonsoft.Json/JsonTextReader.cs) -- or just preprocess your JSON with a Regex. – dbc Jan 26 '17 at 01:06
  • @dbc, preprocessing the JSON to remove the invalid property assignment looks like the most reclaimable solution. If you post this as an answer, I'll accept it as the answer. – mrfelis Jan 30 '17 at 17:16

0 Answers0