如何反序列化无效的json?截断的对象列表 [英] How can I deserialize an invalid json ? Truncated list of objects

查看:140
本文介绍了如何反序列化无效的json?截断的对象列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的json文件主要是一个包含对象的数组,但是列表不完整,所以我不能使用最后一个条目.我想反序列化文件的其余部分,同时丢弃最后一个无效条目

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 discarding the last invalid entry

[ { "key" : "value1" }, { "key " : "value2"}, { "key 

请告诉我是否可以使用Newtonsoft.Json库,还是需要一些预处理.

Please tell me if there is a way using Newtonsoft.Json library, or do I need some preprocessing.

谢谢!

推荐答案

您可以使用JsonReader类,并尝试尽可能地解析.类似于下面的代码,它将解析尽可能多的属性,然后引发异常.当然,如果您想反序列化为一个具体的类,则是这样.

You can use the JsonReader class and try to parse as far as you get. Something like the code below will parse as many properties as it gets and then throw an exception. This is of course if you want to deserialize into a concrete class.

public Partial FromJson(JsonReader reader)
{
    while (reader.Read())
    {
        // Break on EndObject
        if (reader.TokenType == JsonToken.EndObject)
            break;

        // Only look for properties
        if (reader.TokenType != JsonToken.PropertyName)
            continue;

        switch ((string) reader.Value)
        {
            case "Id":
                reader.Read();
                Id = Convert.ToInt16(reader.Value);
                break;

            case "Name":
                reader.Read();
                Name = Convert.ToString(reader.Value);
                break;

        }
    }

    return this;
}

CGbR JSON目标获取的代码.

这篇关于如何反序列化无效的json?截断的对象列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆