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