How can I deserialize an invalid json ? Truncated list of objects

前端 未结 3 433
情书的邮戳
情书的邮戳 2020-11-28 16:16

My json file is mostly an array that contain objects but the list is incomplete, so I can\'t use the last entry. I would like to deserialize the rest of the file while disc

3条回答
  •  借酒劲吻你
    2020-11-28 16:43

    the second answer above is really good and simple, helped me out!

            static string FixPartialJson(string badJson)
            {
                JToken root;
                string exceptionPath = null;
                using (var textReader = new StringReader(badJson))
                using (var jsonReader = new JsonTextReader(textReader))
                using (JTokenWriter jsonWriter = new JTokenWriter())
                {
                    try
                    {
                        jsonWriter.WriteToken(jsonReader);
                    }
                    catch (JsonReaderException ex)
                    {
                        exceptionPath = ex.Path;                    
                    }
                    root = jsonWriter.Token;
                }
    
                return root.ToString();            
            }
    

提交回复
热议问题