如何将现有密钥中的json对象中的值作为数组插入? [英] How to insert value in json object in existing key as a array?
本文介绍了如何将现有密钥中的json对象中的值作为数组插入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
**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
{"Container":[{"ContainerId":"1","ContainerName":"Container1"},
{"ContainerId":"2","ContainerName":"Container2"},
{"ContainerId":"3","ContainerName":"Container3"},
{"ContainerId":"4","ContainerName":"Container4"}]}
This is the code which for reference, Please let me know how I can do this in C#
我尝试过:
What I have tried:
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(); //have to get dispatch payload
//jsonDiaptchObject.Add(propertyDispatch.Key.Insert(0, propertyDispatch.Value));
}
jsonDiaptchObject.Add(propertyDispatch.Key, propertyDispatch.Value);
}
}
stockItem.Payload = jsonDiaptchObject.ToString();
推荐答案
我猜这就是你要找的东西。代码正在寻找一个容纳容器列表的对象。
我建议创建几个对象
I'm guessing this is what you looking for. The code is looking for an object to hold list of container.
I would suggest create couple of Objects
public class Container
{
public string ContainerId { get; set; }
public string ContainerName { get; set; }
}
public class Dispatch
{
public Dispatch()
{
Container = new List<Container>();
}
public List<Container> Container { get; set; }
}
以下是如何填充它的例子
below is an example on how to populate it
//.... Your other code
//initialize the object
var Dispatch = new Dispatch();
foreach (var dispatchItem in packItemRequest.DispatchItems)
{
//.... Your other code
var propertyDispatch = new Container();
propertyDispatch.ContainerId = containerid.ToString();
propertyDispatch.ContainerName = dispatchItem.Container.ToString()
Dispatch.Container.Add(propertyDispatch);
//.... Your other code
}
示例输出(如果正确实施:) :):
Sample output (if implemented correctly :) ):
{
"Container": [
{
"ContainerId": "123",
"ContainerName": "gdfgfdgfd"
},
{
"ContainerId": "222",
"ContainerName": "jhgj,ljkljl"
}
]
}
这篇关于如何将现有密钥中的json对象中的值作为数组插入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文