Skip to content

Insert value dynamically in Json object in existing key

Gaurav Kapahi

Asked Mar 3, 2019, 7:52 AM EST1 answer
Share
LinkedInX
**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#
 
 
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();

1 Answer

Know the answer? Post it. Somebody with the same question will find it here.