[英]How to add json property and value to an empty collection in a jobject?
I have a Jobject
Car
.我有一辆
Jobject
Car
。
The Car
has a null
collection 'wheels'. Car
有一个null
'wheels'。
How could I add property and values to the collection wheels
?我如何向收集
wheels
添加属性和值?
Code:代码:
{
"Car": {
"engine": 2,
"wheels": []
}
}
What I expect:我的期望:
{
"Car": {
"engine": 2,
"wheels": [
{
"frontWheel": 2,
"rearWheel": 2
}
]
}
}
How to add frontwheel
and rearwheel
to the JObject
?如何将
frontwheel
和rearwheel
添加到JObject
?
To create your desired output using Newtonsoft.Json
, you create an instance of JArray
and populate it with instances of type JObject
.要使用
Newtonsoft.Json
创建所需的输出,请创建JArray
的实例并使用JObject
类型的实例填充它。
var result = new JObject(
new JProperty("engine", 2),
new JProperty("wheels",
new JArray
{
new JObject(
new JProperty("frontWheel", 2),
new JProperty("rearWheel", 2))
}));
This will produce the following output:这将产生以下输出:
{
"engine": 2,
"wheels": [
{
"frontWheel": 2,
"rearWheel": 2
}
]
}
Alternatively you could use the serialization mechanism provided by Newtonsoft.Json
或者,您可以使用
Newtonsoft.Json
提供的序列化机制
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.