Last active
October 25, 2024 05:58
-
-
Save itn3000/85d05a3954c6c5c814da524e49556e8a to your computer and use it in GitHub Desktop.
Deserializing JSON Lines test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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