简体   繁体   English

如何将 json 属性和值添加到作业中的空集合?

[英]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 ?如何将frontwheelrearwheel添加到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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM