【问题标题】:Add anonymous or an object properties to JObject in C#在 C# 中向 JObject 添加匿名或对象属性
【发布时间】:2021-12-13 20:22:14
【问题描述】:

我有以下课程

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 格式。我怎样才能实现上述目标?

【问题讨论】:

    标签: c# json class json.net


    【解决方案1】:

    首先,您需要将匿名类型的对象显式转换为 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

    【讨论】:

      猜你喜欢
      • 2011-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-15
      • 2013-06-01
      • 2011-02-05
      相关资源
      最近更新 更多