使用newtonsoft json.net动态创建JSON



我正在尝试创建或实现这种格式的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循环上的项目它告诉它不包含相同的定义等。所以我做错了什么以及如何实现相同的

这是您应该得到您所述的json的结构。代码的问题在于item实际上应该是一个项目列表。

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

您必须创建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);

相关内容

  • 没有找到相关文章