Skip to content

Instantly share code, notes, and snippets.

@itn3000
Last active October 25, 2024 05:58
Show Gist options
  • Save itn3000/85d05a3954c6c5c814da524e49556e8a to your computer and use it in GitHub Desktop.
Save itn3000/85d05a3954c6c5c814da524e49556e8a to your computer and use it in GitHub Desktop.
Deserializing JSON Lines test
using System;
using System.IO;
using System.Text;
using System.Text.Json;
// need System.Text.Json 9.0 or later
namespace jsonserializertest
{
class Program
{
record struct JsonLineValue(string A, int B);
static string GenerateJsonLines()
{
var sb = new StringBuilder();
{
using var sw = new StringWriter(sb);
for(int i = 0;i<10;i++)
{
var str = JsonSerializer.Serialize(new JsonLineValue($"a{i}", i));
sw.WriteLine(str);
}
}
return sb.ToString();
}
static void JsonLinesTest()
{
var str = GenerateJsonLines();
Console.WriteLine($"generated string is '{str}'");
var utf8 = Encoding.UTF8.GetBytes(str);
var jr = new Utf8JsonReader(utf8, new JsonReaderOptions(){ AllowMultipleValues = true });
// Unhandled exception. System.Text.Json.JsonException: The JSON value could not be converted to jsonserializertest.Program+JsonLineValue[]. Path: $ | LineNumber: 0 | BytePositionInLine: 1.
// foreach(var item in JsonSerializer.Deserialize<JsonLineValue[]>(ref jr))
// {
// Console.WriteLine(item);
// }
while(jr.Read())
{
if(jr.TokenType == JsonTokenType.StartObject)
{
var val = JsonSerializer.Deserialize<JsonLineValue>(ref jr);
Console.WriteLine(val.ToString());
}
}
}
static void Main(string[] args)
{
JsonLinesTest();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment