I have Developed the C# Web Method. In this Method Request and Response are Json Array Format.
When I Read Json Array from Post Request, Error Occurred.
My Json Array is
[{"partner_hotel_code": "510","reservation_id": "7660"},{"partner_hotel_code": "510","reservation_id": "7666"}]
Error is
"Type 'System.Collections.Generic.IDictionary`2[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]' is not supported for deserialization of an array."
When i changed the Json into below mentioned format, My method is working Properly.
{"JsonData":[{"partner_hotel_code": "510","reservation_id": "7660"},{"partner_hotel_code": "510","reservation_id": "7666"}]}
But I don't want this format.
Please help, how to rectify the Problem.
You can map that JSON array to List of C# class.
public class RootObject
{
public string partner_hotel_code { get; set; }
public string reservation_id { get; set; }
}
In the web method add parameter List<RootObject> ObjectList
You are getting this error because the Json parameter is required to be an object of key-value pairs , that is:
{"JsonData":[{"partner_hotel_code": "510","reservation_id": "7660"},{"partner_hotel_code": "510","reservation_id": "7666"}]}
{'Key': Value} => Key - JsonData, Value => array of items
With this in mind, you can make your models to match this structure as follows: Prepare a model Item,
public class Item
{
public string partner_hotel_code { get; set; }
public string reservation_id { get; set; }
}
Then prepare a root 'Node' object that will take in a list of the items, let's call it Reservations:
public class Reservations
{
List<Item> JsonData { get; set; }
}
You can then deserialize as shown below:
var data = new JavaScriptSerializer().Deserialize<Reservations>(postData);
But the structure you wanted is something like: [{"partner_hotel_code": "510",...}]
You can achieve this by many ways, an example is using a foreach:
var list = new List<Item>();
foreach(var item in data.JsonData)
{
list.Add(item);
}
/*The value of list here will contain the items*/
listArray[] myArray = list.ToArray();
another solution to this problem is to serialize your array first, then create a JSON object with your method parameter name, and Serialize that... it goes something like this
var myobj = { myArray: JSON.stringify(a) };
passedData = JSON.stringify(myobj);
$.ajax({
type: "POST", contentType: "application/json", data: passedData,
url: window.location.href + "/myMethod",
success: function (result) {
....
}
});
and the webMethod
public static void myMethod(String myArray)
{
dynamic jsonResponse = JsonConvert.DeserializeObject(myArray);
for (var i = 0; i < jsonResponse.Count; i++)
{
...........
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.