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

C# 如何生成以整数为键的json字符串?,c#,json,asp.net-mvc,C#,Json,Asp.net Mvc,我想用C语言生成这样的json字符串 这里有一个问题,“1”:[{},{}],如何生成此部件?顺便说一句,我正在使用asp.net mvc项目,我想将这个json字符串返回到客户端web浏览器。如果您使用的是Newtonsoft.json NuGet包,序列化字典将得到您想要的结果。从NuGet获取。然后,在MVC模型中,对数组属性使用此数据注释 [JsonProperty(PropertyName="1")] public string[] YourProperty { get; set }

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


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

如果您使用的是Newtonsoft.json NuGet包,序列化
字典将得到您想要的结果。

NuGet
获取。然后,在
MVC
模型中,对数组属性使用此
数据注释

[JsonProperty(PropertyName="1")]
public string[] YourProperty { get; set }
当您将数据序列化为
JSON
时,将使用
PropertyName
值,并将以下属性添加到要修改其名称的属性中:

[JsonProperty(PropertyName = "1")]
public List<ObjectName> Objects { get; set; }
[JsonProperty(PropertyName=“1”)]
公共列表对象{get;set;}

有关更多信息,请查看。

此响应可以使用
字典
以数组作为值生成

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

如果它是您的API,那么最好提取
版本
,以使
数据
中的所有对象都是相同类型的,并且类型为
int

的键是1、2、3等。我认为newtonsoft.json dll很有帮助。非常感谢Yeldar,好主意。我将以你的回答作为解决办法。
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" : ""
            }
        ]
    }
}