簡體   English   中英

無法將 Newtonsoft.Json.Linq.JProperty 添加到 Newtonsoft.Json.Linq.JArray

[英]Can not add Newtonsoft.Json.Linq.JProperty to Newtonsoft.Json.Linq.JArray

我正在嘗試重新創建這個 json:

{
"request": {
        " TestRequest": {
            "OrderID": {
                "orderNumber": "12345",
                "category": "ABC"
            },
            "SecondCategory": "DEF"
        }
    }
}

我這樣做:

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")))))
                );

但我收到此錯誤:

無法將Newtonsoft.Json.Linq.JProperty添加到Newtonsoft.Json.Linq.JArray

我究竟做錯了什么? 我該如何解決? 任何幫助,將不勝感激。

謝謝你。

如果您只是創建一個對象,這會容易得多:

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

var reqSer = JsonConvert.SerializeObject(req, Formatting.Indented);

輸出:

{
  "request": {
    "TestRequest": {
      "OrderID": {
        "orderNumber": "12345",
        "category": "ABC"
      },
      "SecondCategory": "DEF"
    }
  }
}

匿名對象不必具有與之關聯的具體類型,只需按照顯示的JSON格式創建格式,然后正常進行序列化即可。

對於聲明式初始化,Ron Beyer 的回答更簡單。 但是您的程序化方法解決了其他需求……而且您已經很接近讓它發揮作用了。

嘗試將 JProperty 添加到 JProperty 的值時,通常會拋出您獲得的異常消息。 雖然我們不能將一個 JProperty 直接放入另一個 JProperty,但我們可以在一個 JProperty 中添加一個 JObject,而這個 JObject 又可以包含 JProperty(ies)。 在這種特定情況下,JProperties“ orderNumber ”和“ category ”周圍缺少 JObject 包裝器

更正后的代碼應如下所示:

JObject jObject = new JObject(new JProperty("request",
              new JObject(
                new JProperty("TestRequest",
                new JObject(
                  new JProperty("OrderID",
                    new JObject(      //********* add a JObject( here 
                        new JProperty("orderNumber", "12345"),
                        new JProperty("category", "ABC"))),  //******* ...and here insert the corresponding closing parenthesis
                    new JProperty("SecondCategory", "DEF")))))
            );



            

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM