如何在返回 JSON 输出时定义数组名称



你好,我对 JSON 很陌生。我编写了一个返回 JSON 输出的方法,如下所示:

[
  {
    "PostId": 0,
    "Title": "BCS",
    "ImageInfo": null,
    "ShortDescription": null,
    "Created": "0001-01-01T00:00:00"
  },
  {
    "PostId": 0,
    "Title": "ABC",
    "ImageInfo": null,
    "ShortDescription": "Corruption",
    "Created": "0001-01-01T00:00:00"
  }
]

我返回输出的方法如下:

public string GetPost(GetPost userPost)
{
    var objPosts = from p in _dbcontext.Posts
                    where p.CategoryId == userPost.CategoryId orderby p.PostId descending
                    select new
                    {
                        Title = p.Title,
                        ImageInfo = p.ImageInfo,
                        ShortDescription = p.ShortDescription,
                    };
    var listEmail = new List<Post>();
    foreach (var item in objPosts)
    {
        var objresult = new Post
        {
           Title = item.Title,
           ImageInfo = item.ImageInfo,
           ShortDescription = item.ShortDescription
        };
        listEmail.Add(objresult);
    }
    string output = JsonConvert.SerializeObject(listEmail);
    return output;
}

我实际上想添加数组名称,以便可以轻松读取我的 JSON 输出。我想要下面这样的东西:

{
  "contacts": [
    {
      "PostId": 0,
      "Title": "BCS",
      "ImageInfo": null,
      "ShortDescription": null,
      "Created": "0001-01-01T00:00:00"
    },
    {
      "PostId": 0,
      "Title": "BCS",
      "ImageInfo": null,
      "ShortDescription": null,
      "Created": "0001-01-01T00:00:00"
    }
  ]
}

请帮忙。

只需将列表更改为字典,如下所示:

var dictionaryEmail = new Dictionary<string, List<Post>>();
var listEmail = var listEmail = new List<Post>();;
foreach (var item in objPosts)
{
    var objresult = new Post
    {
       Title = item.Title,
       ImageInfo = item.ImageInfo,
       ShortDescription = item.ShortDescription
    };
    listEmail.Add(objresult);
}
dictionaryEmail.add("Contacts", listEmail);
string output = JsonConvert.SerializeObject(dictionaryEmail);
return output;

相关内容

  • 没有找到相关文章

最新更新