1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Exception has occurred: CLR/System.Text.Json.JsonException

Last updated at Posted at 2022-11-09

C#でjsonをデシリアライズするときにエラー発生

JsonSerializer.Deserialize<List<T>>(jsonString)の動作に失敗した

Exception has occurred: CLR/System.Text.Json.JsonException
An unhandled exception of type 'System.Text.Json.JsonException' occurred in System.Text.Json.dll: ''c' is an invalid start of a value. Path: $ | LineNumber: 0 | BytePositionInLine: 0.'
 Inner exceptions found, see $exception in variables window for more details.
 Innermost exception 	 System.Text.Json.JsonReaderException : 'c' is an invalid start of a value. LineNumber: 0 | BytePositionInLine: 0.
   at System.Text.Json.ThrowHelper.ThrowJsonReaderException(Utf8JsonReader& json, ExceptionResource resource, Byte nextByte, ReadOnlySpan`1 bytes)
   at System.Text.Json.Utf8JsonReader.ConsumeValue(Byte marker)
   at System.Text.Json.Utf8JsonReader.ReadFirstToken(Byte first)
   at System.Text.Json.Utf8JsonReader.ReadSingleSegment()
   at System.Text.Json.Utf8JsonReader.Read()
   at System.Text.Json.Serialization.JsonConverter`1.ReadCore(Utf8JsonReader& reader, JsonSerializerOptions options, ReadStack& state)

読み込んだJsonの形式が正しくない場合に発生するエラーとのこと
今回の場合、{}ではなく[]で囲また配列になっていた

修正が必要なJsonであっても、オプションによって読み込むことができるものもある

JsonSerializerOptions options = new()
{
    NumberHandling =
        JsonNumberHandling.AllowReadingFromString |
        JsonNumberHandling.WriteAsString,
    WriteIndented = true
};

string forecastJson =
    JsonSerializer.Serialize<Forecast>(forecast, options);

Reference

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?