79 lines
2.4 KiB
C#
79 lines
2.4 KiB
C#
using System.Text.Json;
|
|
using excel_pajak.Models;
|
|
|
|
namespace excel_pajak.Examples;
|
|
|
|
public static class EmployeeJsonExample
|
|
{
|
|
public static void RunExample()
|
|
{
|
|
// Sample JSON from PostgreSQL query
|
|
var json = @"[
|
|
{""employee_number"":""PS2MA001"",""schema"":""_onx4pzkwkeortehfjthgyfkb7c""},
|
|
{""employee_number"":""PS2MA002"",""schema"":""_onx4pzkwkeortehfjthgyfkb7c""},
|
|
{""employee_number"":""PS2MA003"",""schema"":""_onx4pzkwkeortehfjthgyfkb7c""}
|
|
]";
|
|
|
|
// Configure options
|
|
var options = new JsonSerializerOptions
|
|
{
|
|
PropertyNameCaseInsensitive = true,
|
|
WriteIndented = true
|
|
};
|
|
|
|
try
|
|
{
|
|
// Deserialize JSON array to EmployeeInfo[]
|
|
var employees = JsonSerializer.Deserialize<EmployeeInfo[]>(json, options);
|
|
|
|
if (employees != null)
|
|
{
|
|
Console.WriteLine($"Deserialized {employees.Length} employees:");
|
|
foreach (var employee in employees)
|
|
{
|
|
Console.WriteLine($" - {employee.EmployeeNumber} (schema: {employee.Schema})");
|
|
}
|
|
}
|
|
}
|
|
catch (JsonException ex)
|
|
{
|
|
Console.ForegroundColor = ConsoleColor.Red;
|
|
Console.WriteLine($"JSON deserialization error: {ex.Message}");
|
|
Console.ResetColor();
|
|
}
|
|
}
|
|
|
|
public static void TestEmptyArray()
|
|
{
|
|
// Test empty array
|
|
var emptyJson = "[]";
|
|
var options = new JsonSerializerOptions
|
|
{
|
|
PropertyNameCaseInsensitive = true
|
|
};
|
|
|
|
var employees = JsonSerializer.Deserialize<EmployeeInfo[]>(emptyJson, options);
|
|
Console.WriteLine($"Empty array test: {(employees?.Length == 0 ? "PASS" : "FAIL")}");
|
|
}
|
|
|
|
public static void TestMalformedJson()
|
|
{
|
|
// Test malformed JSON
|
|
var malformedJson = "[{invalid json}]";
|
|
var options = new JsonSerializerOptions
|
|
{
|
|
PropertyNameCaseInsensitive = true
|
|
};
|
|
|
|
try
|
|
{
|
|
var employees = JsonSerializer.Deserialize<EmployeeInfo[]>(malformedJson, options);
|
|
Console.WriteLine("Malformed JSON test: FAIL - should have thrown exception");
|
|
}
|
|
catch (JsonException)
|
|
{
|
|
Console.WriteLine("Malformed JSON test: PASS - exception thrown as expected");
|
|
}
|
|
}
|
|
}
|