I'm converting a .NET Framework 4.5 project to .NET Core 3.1. My tests used to use Newtonsoft.Json to check if json is valid and now I would want to implement the same with the built-in System.Text.Json. It appears that
JsonElement values = JsonDocument.Parse(json).RootElement;
throws System.Text.Json.JsonReaderException, but I'm unable to catch this as pointing to this exception results in error
The type or namespace name 'JsonReaderException' does not exist in the namespace 'System.Text.Json' (are you missing an assembly reference?)
I would just want to understand how is it possible that something that doesn't actually seem to exist can be thrown.
Update #1: Stacktrace:
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)
Update #2: I went to see if there would be some nugets that I'm missing. I found System.Text.Json as a nuget (although it was already accessible, I used System.Text.JsonSerializer successfully within the test file). I added it and now I get the actual problem: It is inaccessible due to its protection level.
using System.Text.Json;
namespace System.Text.Json
{
internal sealed class JsonReaderException : JsonException
{
public JsonReaderException(string message, long lineNumber, long bytePositionInLine);
}
}
This doesn't however directly solve, how I can catch this within Assert.Throws<System.Text.Json.JsonReaderException>?
Newtonsoft.Json?JsonReaderExceptionis under the namespaceSystem.Text.Json? I guess it should be under theNewtonsoft.Jsonnamespace, please refer this LINK.JsonReaderExceptionis aNewtonsoft.Jsonspecific exception. You must be still having some dependencies on it as @PavelAnikhouski mentioned.