Gaurav Kapahi

Gaurav Kapahi

  • NA
  • 182
  • 0

Insert value dynamically in Json object in existing key

Mar 3 2019 12:52 PM
**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<string, string>[] propertyDispatchs = new KeyValuePair<string, string>[]
{
        new KeyValuePair<string, string>("ContainerId", containerid.ToString()),
        new KeyValuePair<string, string>("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();

Answers (1)