See if the following would suit your needs.
See full source in one of my GitHub repositories done in Visual Studio 2019, C#8. Make sure to read the readme.md file.
Edit
I added another code sample that actually does a nested property (thought I had before), updated the repository. So the original below has this too.
private void SerializeShipInfoListNestedButton_Click(object sender, EventArgs e)
{
var fileName = "ShipListNested.json";
var (success, createException) = Mockups.ShippingInfoNestedList().ModelToJson(fileName);
if (success)
{
var (shippingInfos, readException) = Helpers.JsonToListModel<ShippingInfo>(fileName);
if (readException == null)
{
foreach (var shippingInfo in shippingInfos)
{
Console.WriteLine($"{shippingInfo.ToString()}");
foreach (var somethingNested in shippingInfo.SomethingNested)
{
Console.WriteLine($@" {somethingNested.Id}, {somethingNested.Value}");
}
Console.WriteLine();
}
}
else
{
MessageBox.Show(readException.Message);
}
}
else
{
MessageBox.Show(createException.Message);
}
}
Original.
using System;
using System.Text;
using System.Windows.Forms;
using JsonCodeSamples.Classes;
using JsonCodeSamples.Models;
namespace JsonCodeSamples
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void SerializeShipInfoButton_Click(object sender, EventArgs e)
{
var fileName = "Ship1.json";
var (success, createException) = Mockups.singleShipInfo().ModelToJson(fileName);
if (success)
{
var (shippingInfo, readException) = Helpers.JsonToModel<ShippingInfo>(fileName);
MessageBox.Show(readException == null ? shippingInfo.ToString() : readException.Message);
}
else
{
MessageBox.Show(createException.Message);
}
}
private void SerializeShipInfoListButton_Click(object sender, EventArgs e)
{
var fileName = "ShipList.json";
var (success, createException) = Mockups.ShippingInfoList().ModelToJson(fileName);
if (success)
{
var (shippingInfos, readException) = Helpers.JsonToListModel<ShippingInfo>(fileName);
if (readException == null)
{
var sb = new StringBuilder();
shippingInfos.ForEach(item => sb.AppendLine(item.ToString()));
MessageBox.Show(sb.ToString());
}
}
else
{
MessageBox.Show(createException.Message);
}
}
}
}
single instance json
{
"AddressDetails": {
"Street": "1 Maple Drive",
"City": "Portland",
"State": "OR",
"PostalCode": "97666"
},
"FirstName": "Jim",
"LastName": "Adams",
"Gender": 0
}
list json
[
{
"AddressDetails": {
"Street": "1 Maple Drive",
"City": "Portland",
"State": "OR",
"PostalCode": "97666"
},
"FirstName": "Jim",
"LastName": "Adams",
"Gender": 0
},
{
"AddressDetails": {
"Street": "1 Maple Drive",
"City": "Portland",
"State": "OR",
"PostalCode": "97666"
},
"FirstName": "Mary",
"LastName": "Adams",
"Gender": 1
}
]
---