如何在c#中向对象追加数据?

本文关键字:对象 追加 数据 | 更新日期: 2023-09-27 18:09:49

所以在c#中我创建了以下Json:

{
"timeline": {
    "headline": "Development timeline",
    "type": "default",
    "text": "timeline",
    "startDate": "12/12/2011",
    "date": [
        {
            "startDate": "2012,02,15",
            "endDate": "2012,04,19",
            "headline": "Development",
            "text": "Coding"
        },
        {
            "startDate": "2012,04,19",
            "endDate": "2012,07,25",
            "headline": "Development",
            "text": "Coding"
        },
        {
            "startDate": "2012,07,25",
            "endDate": "2012,10,26",
            "headline": "Development",
            "text": "Coding"
        }
    ]
}

}

使用jobobject:

                jjson = new JObject(
               new JObject(
                new JProperty("timeline",
                    new JObject(
                    new JProperty("headline", "Development"),
                    new JProperty("type", "default"),
                    new JProperty("text", "timeline"),
                    new JProperty("startDate", "12/12/2011"),
                    new JProperty("date",
                        new JArray(
                        from p in timelineList
                        orderby p.releaseDate
                        select new JObject(
                            new JProperty("startDate", p.startDate),
                            new JProperty("endDate", p.endDate),
                            new JProperty("headline", p.headline),
                            new JProperty("text", p.text))                                
                            ))))));

现在我希望在json对象的date[]中添加另一个具有开始日期/结束日期的部分然而,我似乎不能这样做:

我试图创建另一个JArray只是为了测试,看看它是否会追加到我的json,但没有运气,因为我得到一个错误:"引用不设置为对象的实例:

JArray dd = new JArray();
dd = (JArray) jjson["date"];
dd.Add("item 1,sdsds");

我如何添加另一个属性到我已经创建的JSON?谢谢你

如何在c#中向对象追加数据?

从你的例子中,jjson不包含date属性,它只包含timeline属性,所以在你的情况下,它应该是((JSonObject)jjson["timeline"])["date"]