【问题标题】:How to define Array name while returning JSON output如何在返回 JSON 输出时定义数组名称
【发布时间】:2013-12-27 08:44:03
【问题描述】:

你好,我是 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"
    }
  ]
}

请帮忙。

【问题讨论】:

    标签: c#-4.0 json.net json


    【解决方案1】:

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

    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;
    

    【讨论】:

    • 我正要给出我的问题的答案,但以某种不同的方式。我正在传递带有输出的静态字符串,例如:return "{" + "Contacts" + output + "}"。
    • 嗯,根据我的经验,像这样改变序列化输出是不好的做法,因为你会遇到一些依赖于 json 序列化函数的方法,而你对此无能为力。跨度>
    猜你喜欢
    • 2020-12-11
    • 2020-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-16
    • 1970-01-01
    • 2022-01-25
    相关资源
    最近更新 更多