如何在C#中将数据附加到JObject?

时间:2013-04-18 18:29:48

标签: c# json

所以在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"
        }
    ]
}

}

使用JObject:

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

现在我希望用startdate / enddate在json对象的date []中添加另一个部分 但是我似乎无法做到这一点:(

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

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

如何在已创建的JSON中添加其他属性? 谢谢

1 个答案:

答案 0 :(得分:0)

从您的示例jjson不包含date属性,它只包含timeline属性,因此在您的情况下应该是((JSonObject)jjson["timeline"])["date"]