【问题标题】:How to Convert form inputs to json array and send it as http post request in body, using c# in mvc5如何在 mvc5 中使用 c# 将表单输入转换为 json 数组并将其作为 http post 请求发送到正文中
【发布时间】:2018-11-29 21:21:05
【问题描述】:

这就是我想要的(json 数组): [{"location":"uk","keyword":"developer","specialization":"asp.net","lat":"28.5654"},"long":78.3265"]`

这是我尝试获取的 json 数组:

var list = new List<KeyValuePair<string, string>>();

        list.Add(new KeyValuePair<string, string>("Name", query.Name));
        list.Add(new KeyValuePair<string, string>("Specialization", query.Specialization));

        var json = JsonConvert.SerializeObject(list);

这是结果:[{"Key":"Name","Value":"Sam"},{"Key":"Specialization","Value":"ASP.Net"}]

但我想要这样: [{"Name":"Sam","Specialization":"ASP.Net"}]

【问题讨论】:

  • 您能提供给我们您的控制器吗?那会很有帮助。需要知道您的控制器操作方法是采用数组还是对象。

标签: c# asp.net-mvc post http-post webrequest


【解决方案1】:

哦,对了,所以我认为解决方案是使用字典而不是 KeyValuePair:

var list = new Dictionary<string,string>();

list.Add("location", mysearch.location);
list.Add("keyword", mysearch.keyword);
...

var listSerialized= JsonConvert.Serialize(list);

如果你需要一个数组,你可以这样做:

var dictionaryList = new List<Dictionary<string, string>>();

foreach(search in mySearchList)
{
    var item = new Dictionary<string,string>();
    item.Add("location", search.location);
    item.Add("keyword", search.keyword);
    ...

    dictionaryList.Add(item);
}
var serializedArray = JsonConvert.Serialize(jsonArray);

【讨论】:

    【解决方案2】:

    嗯,我认为您确实需要一个键值对列表而不是一个数组,试试这个:

    var list = new List<KeyValuePair<string,string>>();
    list.Add(new KeyValuePair<string,string>("location": mysearch.location);
    list.Add(new KeyValuePair<string,string>("keyword": mysearch.keyword);
    ...
    

    您可以将其用作您的正文请求,但如果您需要一个数组,您可以这样做:

    var array = list.ToArray();
    

    关于如何发起 http post 请求的帮助,可以参考这篇文章: How to make HTTP POST web request

    希望对你有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-03
      • 1970-01-01
      相关资源
      最近更新 更多