c# - 如何生成以整数为键的json字符串?

标签 c# json asp.net-mvc

我想用C#语言生成这样的json字符串

{
  "error": "0",
  "message": "messages",
  "data": {
    "version": "sring",
    "1": [
      {
        "keyword": "",
        "title": ""
      },
      {
        "keyword": "",
        "title": ""
      }
    ],
    "2": [
      ...
    ],
    "3": [
      ...
    ]
  }
}

这里有个问题,"1":[{},{}],这部分如何生成?顺便说一句,我正在使用 asp.net mvc 项目,我想将此 json 字符串返回给客户端 Web 浏览器。

最佳答案

可以使用 Dictionary<string, object> 简单地生成此响应以数组作为值。

public class KeywordTitle
{
    public string keyword { get; set; }
    public string title { get; set; }
}

public class Response
{
    public string error { get; set; }
    public string message { get; set; }
    public Dictionary<string, object> data { get; set; }
}

var dictionary = new Dictionary<string, object> {
    {"version", "sring"}
};

dictionary.Add("1", new []
{
    new KeywordTitle { keyword = "", title = "" },
    new KeywordTitle { keyword = "", title = "" },
    new KeywordTitle { keyword = "", title = "" }
});

JsonConvert.SerializeObject(new Response
{
    error = "0",
    message = "messages",
    data = dictionary
});

它产生:

{
    "error" : "0",
    "message" : "messages",
    "data" : {
        "version" : "sring",
        "1" : [{
                "keyword" : "",
                "title" : ""
            }, {
                "keyword" : "",
                "title" : ""
            }, {
                "keyword" : "",
                "title" : ""
            }
        ]
    }
}

如果它是您的 API,那么最好提取 version为了使所有对象在data类型相同,键类型为 int .

关于c# - 如何生成以整数为键的json字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33868663/

相关文章:

c# - excel表格中的SQL查询语句

c# - 为什么 Authentication Cookie 对 [Authorize] 属性不起作用?

javascript - 如何使用 php sql 查询让事件显示在日历中?

.net - 使用 Azure AD 凭据连接 CRM Web 服务

c# - C# lambda 表达式的参数类型推断中的歧义

php - 打印嵌套数组 PHP

php - 如何递归搜索和替换未知深度多维 PHP 数组中的值?

asp.net-mvc - Asp.net MVC 4 API 和 Knockout.js : Generate Knockout. js 模型

c# - 是否可以为 ASP.NET MVC 路由提供比其他路由更多的服务器资源?

c# - 无法将当前 JSON 对象(例如 {"name":"value"})反序列化为类型 'System.Collections.Generic.List` 1