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

查看:21
本文介绍了如何反序列化无效的 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天全站免登陆