【发布时间】:2020-09-09 00:15:50
【问题描述】:
我正在将 .NET Framework 4.5 项目转换为 .NET Core 3.1。我的测试曾经使用 Newtonsoft.Json 来检查 json 是否有效,现在我想用内置的 System.Text.Json 来实现它。看来
JsonElement values = JsonDocument.Parse(json).RootElement;
抛出System.Text.Json.JsonReaderException,但我无法捕捉到这一点,因为指向此异常会导致错误
命名空间“System.Text.Json”中不存在类型或命名空间名称“JsonReaderException”(您是否缺少程序集引用?)
我只是想了解如何可能抛出实际上似乎并不存在的东西。
更新#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: 我去看看是否会有一些我错过的nugets。我发现 System.Text.Json 是一个 nuget(虽然它已经可以访问,但我在测试文件中成功使用了 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> 中捕捉到这个?
【问题讨论】:
-
你能提供堆栈跟踪和 json 示例吗?您是否删除了与
Newtonsoft.Json相关的所有内容? -
您确定
JsonReaderException在命名空间System.Text.Json下吗?我猜它应该在Newtonsoft.Json命名空间下,请参考这个LINK。 -
JsonReaderException是Newtonsoft.Json特定的例外。正如@PavelAnikhouski 提到的那样,您一定仍然对它有一些依赖。 -
@PavelAnikhouski 在堆栈跟踪之后您是否仍然认为它可能与 Newtonsoft 有关?无效 json 的示例是空字符串。
标签: c# json .net-core nunit system.text.json