NewtonSoft Json无效强制转换异常

本文关键字:转换 异常 Json 无效 NewtonSoft | 更新日期: 2023-09-27 18:06:22

这与我的问题HTTPClient Buffer超过2G有关;不能向缓冲区写入更多的字节,但在我看来,这是一个不同的问题。

在另一个问题中,我试图找出如何处理打破2G请求缓冲区。我的想法是使用流媒体,但我需要反序列化。在与Google教授交谈时,我发现我必须使用TextReader来流式传输/反序列化。我的代码是:

    public async Task<API_Json_Special_Feeds.RootObject> walMart_Special_Feed_Lookup(string url)
    {
        special_Feed_Lookup_Working = true;
        HttpClientHandler handler = new HttpClientHandler()
        {
            AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate
        };
        using (HttpClient http = new HttpClient(handler))
        {
            http.DefaultRequestHeaders.AcceptEncoding.Add(new System.Net.Http.Headers.StringWithQualityHeaderValue("gzip"));
            http.Timeout = TimeSpan.FromMilliseconds(Timeout.Infinite);
            url = String.Format(url);
            using (var response = await http.GetAsync(url, HttpCompletionOption.ResponseHeadersRead))
            {
                Console.WriteLine(response);
                var serializer = new JsonSerializer();
                using (StreamReader sr = new StreamReader(await response.Content.ReadAsStreamAsync()))
                {
                    using (var jsonTextReader = new JsonTextReader(sr))
                    {
                        API_Json_Special_Feeds.RootObject root = (API_Json_Special_Feeds.RootObject)serializer.Deserialize(jsonTextReader);
                        return root;
                    }
                }
            }
        }
    }

现在可以看到,返回类型是强类型的。方法的返回类型匹配。现在,我转到主叫行:

  API_Json_Special_Feeds.RootObject Items = await net.walMart_Special_Feed_Lookup(specialFeedsURLs[i].Replace("{apiKey}", Properties.Resources.API_Key_Walmart));
所以,我们有匹配的类型API_Json_Special_Feeds。

运行时,调用行抛出InvalidCastException:

不良结果:

Unable to cast object of type 'Newtonsoft.Json.Linq.JObject' to type 'RootObject'

我在返回之前检查了方法的末尾,结果确实从对象转换为API_Json_Special_Feeds。RootMethod,然后返回。

问题:在返回语句和调用行之间的某个地方,被返回的对象是从API_Json_Special_Feeds转换而来的。RootMethod到Newtonsoft.Json.Linq.JObject。我无法调试它,因为中间没有代码。如果我在调用行中再次强制转换,就会得到"不能强制转换"错误。如何防止此对象类型的降级/更改?

非常,非常感谢您的时间,考虑,以及您可以提供的任何想法或建议!

NewtonSoft Json无效强制转换异常

您需要使用泛型重载JsonSerializer.Deserialize<T>()

var root = serializer.Deserialize<API_Json_Special_Feeds.RootObject>(jsonTextReader);

BinaryFormatter生成的文件不同,JSON文件通常不包含c#类型信息,因此接收系统有必要指定期望的类型。

JSON标准有一些扩展,其中c#类型信息可以包含在JSON文件中——例如JSON。. NET的TypeNameHandling——但仍有必要将JSON反序列化为适当的显式基类。

参见从文件反序列化JSON了解从流反序列化强类型c#对象的另一个示例。