使用newtonsoft json.net使用动态创建JSON

时间:2015-09-01 11:17:00

标签: c# json windows-phone-8 json.net

我正在尝试以这种格式创建或分发json

   {

     "title": "Star Wars",
    "link": "http://www.starwars.com",
    "description": "Star Wars blog.",
    "item": [
       {
         "title": "Episode VII",
         "description": "Episode VII production",
         "link": "episode-vii-production.aspx"
        },
        {
         "title": "Episode VITI",
         "description": "Episode VII production",
         "link": "episode-vii-production.aspx"
        }


        ]
       }

我正在尝试这个实现这个

 dynamic o = new ExpandoObject();

o.title= "fdsfs";
o.link= "fsrg";
o.description="fdsfs";
      foreach (var adata in all)
                {
                o.item.title="fgfd";
                o.item.description="sample desc";
                o.item.link="http://google.com"
                } 
 string json = JsonConvert.SerializeObject(o);

但是在这里它会在foreach循环上抛出异常,因为它告诉它不包含相同的等等。所以我做错了以及如何实现相同的

2 个答案:

答案 0 :(得分:2)

这就是你应该得到你所说的json的结构。您的代码存在的问题是该项目实际上应该是项目列表。

public class Item
{
    public string title { get; set; }
    public string description { get; set; }
    public string link { get; set; }
}

public class RootObject
{
    public string title { get; set; }
    public string link { get; set; }
    public string description { get; set; }
    public List<Item> item { get; set; }
}

然后你可以使用这段代码:

 dynamic o = new ExpandoObject();

o.title= "fdsfs";
o.link= "fsrg";
o.description="fdsfs";
o.item = new List<ExpandoObject>();  
//although list of dynamics is not recommended as far as I remember
      foreach (var adata in all)
                {
                o.item.Add(new Item(){   
                title="fgfd",
                description="sample desc",
                link="http://google.com" });
                } 
 string json = JsonConvert.SerializeObject(o);

答案 1 :(得分:1)

您必须创建o.item才能为其指定值:

dynamic o = new ExpandoObject();
var all = new object[] { new object() };

o.title= "fdsfs";
o.link= "fsrg";
o.description="fdsfs";
var items = new List<ExpandoObject>();
foreach (var adata in all)
{
    dynamic item = new ExpandoObject();
    item.title="fgfd";
    item.description="sample desc";
    item.link="http://google.com";
    items.Add(item);
} 
o.item = items;
string json = JsonConvert.SerializeObject(o);