【问题标题】:Adding array into POST parameters C#将数组添加到 POST 参数 C#
【发布时间】:2021-08-02 14:37:10
【问题描述】:

我想在我的 POST 参数中添加类似这样的内容(如下所示):

{"DaysBefore": 5,
"IdList": [
5,
9,
13,
14
 ],
"pId": 1,
"mId": 1
}

我有一个这样的字典:

var postData = new Dictionary<string, string>();
postData.Add("IdList","b")

Insted of b 我如何添加 [ 5、 9、 13, 14 ] 那里?

我想使用 C# 将Generic.List() 发送到后端

【问题讨论】:

  • 看来你需要发布一个 JSON 对象;您应该使用 JSON 序列化程序而不是字典。
  • 您发布的是单个 JSON 文档,而不是多个查询参数。它是一个 object,其 IdList 属性包含一个数值数组。不涉及“通用列表”

标签: c# arrays asp.net dictionary


【解决方案1】:

我会将其解析为 Json。无需将数组作为字符串拉入,然后必须将其解析为 int 列表。

    public static void Main()
{
        var foo = @"{""DaysBefore"": 5,
            ""IdList"": [
            5,
            9,
            13,
            14
             ],
            ""pId"": 1,
            ""mId"": 1
            }";
            
    var result = JsonConvert.DeserializeObject<Data>(foo);
    
    Console.WriteLine("DaysBefore: " + result.DaysBefore);
    Console.WriteLine("idList: " + String.Join(", ", result.idList));
    Console.WriteLine("mId: " + result.mId);
    Console.WriteLine("pId: " + result.pId);

}
                                           
public class Data
{
    public string DaysBefore {get; set;}
    public List<int> idList{ get; set;}
    public int pId {get; set;}
    public int mId {get; set;}
}

Working example

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 2011-09-20
    • 2016-04-07
    • 1970-01-01
    相关资源
    最近更新 更多