**Below code output**: I am able to get json as below by this code
{
"ContainerId": "848dc1ca-04ae-457e-b6ac-0dee454816c4",
"ContainerName": "Container1"
}
**Needed Output**: But I want to insert value dynamically like below json in array that contains multiple container ID and Container Name
I have to make json like this
{
"ContainerId": ["848dc1ca-04ae-457e-b6ac-0dee454816c4",
"aj8dc1ca-04ae-457e-b6ac-0dee454816c4"],
"ContainerName": ["Container1","Container2"]
}
This is the code which for reference, Please let me know how I can do this in C#
var jsonDiaptchObject = JObject.Parse(stockItem.Payload);
var oldDispatchItem = await _stockItemService.GetStockItemFor(stockItem.Identifier);
foreach (var dispatchItem in packItemRequest.DispatchItems)
{
containerid = Guid.NewGuid();
KeyValuePair[] propertyDispatchs = new KeyValuePair[]
{
new KeyValuePair("ContainerId", containerid.ToString()),
new KeyValuePair("ContainerName", dispatchItem.Container.ToString())
};
string olddispatchValue = null;
foreach (var propertyDispatch in propertyDispatchs)
{
if (jsonDiaptchObject.ContainsKey(propertyDispatch.Key))
{
olddispatchValue = JObject.Parse(stockItem.Payload) [propertyDispatch.Key]?.ToString();
//jsonDiaptchObject.Add(propertyDispatch.Key.Insert(0, propertyDispatch.Value));
}
jsonDiaptchObject.Add(propertyDispatch.Key, propertyDispatch.Value);
}
}
stockItem.Payload = jsonDiaptchObject.ToString();
Vivek KumarPosted Mar 4, 2019, 12:23 PM
Hi,
You have to use consistency in values if you are using an array then from very first use as an array as I see in your question that ContainerId and ContainerName is not an array but in output, it is an array so, I will suggest that you will use array type from very first.
Please take help from below links.
https://stackoverflow.com/questions/33081102/json-add-new-object-to-existing-json-file-c-sharp/33081258
https://stackoverflow.com/questions/38908830/json-net-to-add-append-new-object-item-into-existing-json-object
https://www.newtonsoft.com/json/help/html/ModifyJson.htm
https://www.c-sharpcorner.com/article/crud-operation-with-json-file-data-in-c-sharp/