62 lines
2.4 KiB
C#
62 lines
2.4 KiB
C#
#nullable enable
|
|
using BCG;
|
|
|
|
using System;
|
|
using System.Text.Json;
|
|
using System.Text.Json.Serialization;
|
|
|
|
namespace Bts.DataStreamCore;
|
|
|
|
class BlueRowJsonConverter : JsonConverter<IBlueRow> {
|
|
IBlueTableSchema? schema = null;
|
|
|
|
public override IBlueRow Read(
|
|
ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) {
|
|
if (schema is null) {
|
|
throw new InvalidOperationException("Cannot read row from json because schema is null");
|
|
}
|
|
var mbr = new MutableBlueRow(schema);
|
|
int colNum = 0;
|
|
switch (reader.TokenType) {
|
|
case JsonTokenType.StartArray:
|
|
while (reader.Read() && reader.TokenType != JsonTokenType.EndArray) {
|
|
mbr.setValue(colNum++, readCellValue(ref reader));
|
|
colNum++;
|
|
}
|
|
break;
|
|
case JsonTokenType.StartObject:
|
|
while (reader.Read() && reader.TokenType != JsonTokenType.EndObject) {
|
|
if (reader.TokenType != JsonTokenType.PropertyName) {
|
|
throw new InvalidOperationException(
|
|
"Expected 'PropertyName' immediately after 'StartObject' token in row json");
|
|
}
|
|
var colName = reader.GetString();
|
|
if (!reader.Read()) {
|
|
throw new InvalidOperationException(
|
|
"Failed to read token immediately after 'PropertyName' token in row json");
|
|
}
|
|
mbr.setValue(colName, readCellValue(ref reader));
|
|
}
|
|
break;
|
|
}
|
|
if (mbr.Count != schema.columnInfo.Length) {
|
|
throw new InvalidOperationException(
|
|
$"Row json array length '{mbr.Count}' does not match the schema's " +
|
|
$"column length '{schema.columnInfo.Length}'.");
|
|
}
|
|
return mbr;
|
|
|
|
static object? readCellValue(ref Utf8JsonReader reader) =>
|
|
reader.TokenType switch {
|
|
JsonTokenType.String => reader.GetString(),
|
|
JsonTokenType.Number => reader.GetDouble(),
|
|
JsonTokenType.True or JsonTokenType.False => reader.GetBoolean(),
|
|
_ => throw new InvalidOperationException("Failed to read cell value"),
|
|
};
|
|
}
|
|
|
|
public override void Write(Utf8JsonWriter writer, IBlueRow value, JsonSerializerOptions options) {
|
|
throw new NotImplementedException();
|
|
}
|
|
}
|