无法将 Newtonsoft.Json.Linq.JProperty 添加到 Newtonsoft.Json.Linq.JArray

Abh*_*bhi 5 .net c# json

我正在尝试重新创建这个 json:

{
"request": {
        " TestRequest": {
            "OrderID": {
                "orderNumber": "12345",
                "category": "ABC"
            },
            "SecondCategory": "DEF"
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在这样做:

JObject jObject = new JObject(new JProperty("request",
                  new JObject(
                    new JProperty("TestRequest",
                    new JObject(
                        new JProperty("OrderID",
                            new JProperty("orderNumber", "12345"),
                            new JProperty("category", "ABC")),
                            new JProperty("SecondCategory", "DEF")))))
                );
Run Code Online (Sandbox Code Playgroud)

但我收到这个错误:

无法添加Newtonsoft.Json.Linq.JPropertyNewtonsoft.Json.Linq.JArray

我究竟做错了什么?我该如何解决它?任何帮助,将不胜感激。

谢谢。

Ron*_*yer 3

如果你只创建一个对象,这会容易得多:

var req = new
{
    request = new
    {
        TestRequest = new
        {
            OrderID = new
            {
                orderNumber = "12345",
                category = "ABC"
            },
            SecondCategory = "DEF"
        }
    }
};

var reqSer = JsonConvert.SerializeObject(req, Formatting.Indented);
Run Code Online (Sandbox Code Playgroud)

输出:

{
  “要求”: {
    “测试请求”:{
      “订单ID”:{
        "订单号": "12345",
        “类别”:“ABC”
      },
      “第二类”:“DEF”
    }
  }
}

匿名对象不必具有与其关联的具体类型,只需创建几乎与您显示的 JSON 相同的格式,然后正常序列化它。