如何将表单输入转换为 json 数组并将其作为 http post 请求在正文中发送,在 mvc5 中使用 c#

How to Convert form inputs to json array and send it as http post request in body, using c# in mvc5

This is what I want (json array): [{"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);

This is the result: [{"Key":"Name","Value":"Sam"},{"Key":"Specialization","Value":"ASP.Net"}]

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

嗯,我认为你真的需要一个键值对列表而不是一个数组,试试这个:

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 请求的帮助,您可以参考此 post:

希望对您有所帮助。

哦对了,所以我认为解决方案是使用字典而不是 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);