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



这就是我想要的(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"}]

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

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

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帖子请求的帮助,您可以查阅以下帖子:如何使HTTP POST web请求

我希望能帮上忙。

最新更新