在 C# 中向 JObject 添加匿名或对象属性

Add anonymous or an object properties to JObject in C#

我关注class

public class Customer{
  public string name {get;set;}
  public JObject properties {get;set;} = new JObject();
}

现在我正在向客户属性中添加属性

var customer = new Customer();

customer.properties["wow-123:test"] =  new { 
    name = "Mark, 
    company = new  { 
            name = "LLC",
            address = new  {
city= "London" } } }

最后我希望它看起来像这样:

    "properties": {
      "wow-123:test": [
        {
          "name": "Mark",
          "company": {
            "name": "LLC",
            "address ": {
              "city": "London"
            }
          }
        }
      ]
    }

我一直收到无法将其转换为 Jtoken 的错误。如果我将它更改为 ToString,则它不是 JSON 格式。我怎样才能实现上述目标?

首先,您需要将匿名类型的对象显式转换为 JToken:

customer.properties["wow-123:test"] = JToken.FromObject(new { ... });

但是,由于您的示例输出显示 wow-123:test 的内容是 array (..."wow-123:test": [ { "name":...) ,因此您实际需要的可能是

customer.properties["wow-123:test"] = new JArray(JToken.FromObject(new { ... } ));

这将创建一个包含匿名类型对象的单元素数组。

fiddle