In C# I want to created JSON String or Object with the format below:
{
"retailer_br_id" : "5473182",
"retailer_external_id": "",
"erp_invoice_number" : "INV-202302",
"invoice_date": "2023-04-06T17:00:00.000Z",
"status" : 1,
"details":[{
"sku_external_id": "TD5015151432201",
"quantity" : "2",
"price_per_item": "14.5"
},
{
"sku_external_id": "000005020170898446",
"quantity" : 1,
"price_per_item": 10.50
}
]
}
I tried the following, but it seems not working, it only gives me the dList value…………………………………………………………………………………………………………………..
DataTable dt = new DataTable("Details");
dt.Columns.Add("sku_external_id", typeof(string));
//Data
dt.Rows.Add("0000000000");
dt.Rows.Add("111111111");
dt.Rows.Add("1222222222");
dt.Rows.Add("3333333333");
Root rt = new Root();
rt.retailer_br_id = "32423432432424";
rt.retailer_external_id = "";
rt.erp_invoice_number = "PBY-202304";
DateTime d = DateTime.Now;
string dateString = d.ToString("Y-m-d H:i:s");
rt.invoice_date = dateString;
List<Detail> dList = new List<Detail>();
for (int i = 0; i < dt.Rows.Count; i++)
{
Detail det = new Detail();
det.sku_external_id = (string)dt.Rows[i]["sku_external_id"];
dList.Add(det);
}
string json = JsonConvert.SerializeObject(dList, Formatting.Indented);
textBox1.Text = json;
3
Answers
You are serializing
dList
, but notroot
, this is why it show the serializeddList
.Missing assign the
dList
tort.details
.Alternatives
foreach
loop to iterate and add items intodList
, you may achieve with:JsonProperty
attribute to define the property name used in serialization and deserialization.invoice_date
property toDateTime
type so it will serialize and display the format in ISO 8601, instead of defining the format manually.The json will only have the value of dList, because you have not assigned
rt
to thedet
object. I am assuming thatdet
has a property which can be assigned to with the value of rt e.g.if
det
does not have a property of type root, you will need to add one.It may be that you do not want
root
to be assigned to each instance ofdet
to the list. If you want to assign it once outside the list then you would need a wrapper object eg.The modified code will then look like…
you can just use an anonymous type
now if you want, you can convert this JSON to a C# classes online
using this link for example https://json2csharp.com/