[英]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数组):[{“ location”:“ uk”,“ keyword”:“ developer”,“ specialization”:“ asp.net”,“ lat”:“ 28.5654”},“ long” :78.3265" ]`
This is what I tried to get json array: 这是我尝试获取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"}]
结果是:[{{Key“:” Name“,” Value“:” Sam“},{” Key“:” Specialization“,” Value“:” ASP.Net“}]
But I want it like this: [{"Name":"Sam","Specialization":"ASP.Net"}] 但是我想要这样: [{“ Name”:“ Sam”,“ Specialization”:“ ASP.Net”}]
Hmmm, I think you really need a list of key value pair instead an array, try this: 嗯,我认为您确实需要键值对列表而不是数组,请尝试以下操作:
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);
...
You can use this as your body request, but if you need an array you can do: 您可以使用此请求作为正文请求,但是如果需要一个数组,则可以执行以下操作:
var array = list.ToArray();
For help how to make an http post request, you can consult this post: How to make HTTP POST web request 要获得有关如何发出http帖子请求的帮助,您可以查阅此帖子: 如何发出HTTP POST Web请求
I hope be helpfull. 希望对您有所帮助。
Oh right, so I think the solution is use a Dictionary instead KeyValuePair: 哦,对了,所以我认为解决方案是使用Dictionary而不是KeyValuePair:
var list = new Dictionary<string,string>();
list.Add("location", mysearch.location);
list.Add("keyword", mysearch.keyword);
...
var listSerialized= JsonConvert.Serialize(list);
If you need an array you can do this: 如果需要数组,可以执行以下操作:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.