Can I deserialize a JSON text until error or end with Newtonsoft parser?

Viewed 74

I have a bunch of JSON files that I need to process; I'm doing it this way:

var settings = new JsonSerializerSettins
{
    Error = delegate(object sender, Newtonsoft.Json.Serialization.ErrorEventArgs args)
    {
        Log_The_Error();
        args.ErrorContext.Handled = true;
    }
};

foreach (var jsonFile in directory.GetFiles("*.json"))
{
    using (StreamReader file = File.OpenText(jsonFile.FUllName))
    {
        try
        {
            var data = JsonConvert.DeserializeObject<JObject>(file.ReadToEnd(), settings);

            if (data != null)
            {
                // Do fancy things...
            }
        }
        catch (Exception e)
        {
            Log_The_Exception();
        }
    }
}

Some of the json files appears to be truncated so the inner json object is not valid but, even if the data is truncated I can use the partial data I already received, the json text looks like:

{
    "property1": 1,
    "property2": 2,
    "property3": 3,
    "property4": 4,
    "array": {
        "amount": 9999
        "array": [
            { ... },
            { ... },
            ... Hundreds of json objects ...
            { ... },
            { ... }
        ]
    }
}

Some files are truncated at array.array level:

{
    "property1": 1,
    "property2": 2,
    "property3": 3,
    "property4": 4,
    "array": {
        "amount": 9999
        "array": [
            { ... },
            { ... },
            ... Hundreds of json objects ...
            { ... },
            ... end of file ...

Whenever this happens, the JsonConvert.DeserializeObject returns null, is there a way to get the data until the parsing error occurs instead of a null value?

0 Answers
Related