我正在将一个.NET Framework 4.5项目转换为.NET Core 3.1。 我的测试以前使用Newtonsoft.Json来检查json是否有效,现在我想使用内置的System.Text.Json来实现相同的功能。 看起来
JsonElement values = JsonDocument.Parse(json).RootElement;
抛出了 System.Text.Json.JsonReaderException
异常,但我无法捕获此异常,因为指向该异常会导致错误。
'JsonReaderException' 类型或命名空间不存在于 'System.Text.Json' 命名空间中(是否缺少程序集引用?)
我只是想了解一下,为什么可能会抛出实际上似乎并不存在的东西。
更新 #1: 堆栈跟踪:
at System.Text.Json.ThrowHelper.ThrowJsonReaderException(Utf8JsonReader& json, ExceptionResource resource, Byte nextByte, ReadOnlySpan`1 bytes)
at System.Text.Json.Utf8JsonReader.ReadSingleSegment()
at System.Text.Json.Utf8JsonReader.Read()
at System.Text.Json.JsonDocument.Parse(ReadOnlySpan`1 utf8JsonSpan, Utf8JsonReader reader, MetadataDb& database, StackRowStack& stack)
at System.Text.Json.JsonDocument.Parse(ReadOnlyMemory`1 utf8Json, JsonReaderOptions readerOptions, Byte[] extraRentedBytes)
at System.Text.Json.JsonDocument.Parse(ReadOnlyMemory`1 json, JsonDocumentOptions options)
at System.Text.Json.JsonDocument.Parse(String json, JsonDocumentOptions options)
at Anonymized..ctor(String json) in Anonymized.cs:line 182
at Anonymized.<>c__DisplayClass12_0.<TestCreateLogEntryFromJson_IllegalValues>b__0() in Anonymized.cs:line 206
at NUnit.Framework.Assert.Throws(IResolveConstraint expression, TestDelegate code, String message, Object[] args)
更新 #2: 我去查看是否有我缺失的 NuGet 包。我在 NuGet 上找到了 System.Text.Json(尽管已经可访问,我仍在测试文件中成功使用了 System.Text.JsonSerializer)。我添加了它,现在我遇到了实际问题:它由于其保护级别而无法访问。
using System.Text.Json;
namespace System.Text.Json
{
internal sealed class JsonReaderException : JsonException
{
public JsonReaderException(string message, long lineNumber, long bytePositionInLine);
}
}
然而,这并没有直接解决我如何在Assert.Throws<System.Text.Json.JsonReaderException>
中捕获它的问题。
Newtonsoft.Json
相关的内容吗? - Pavel AnikhouskiJsonReaderException
在命名空间System.Text.Json
下吗?我猜应该在Newtonsoft.Json
命名空间下,请参考这个链接。 - Shawn XiaoJsonReaderException
是Newtonsoft.Json
特定的异常。正如 @PavelAnikhouski 所提到的,您可能仍然对它有一些依赖关系。 - Eldar