Reputation: 312
I have JSON as such:
EDITED: JSON was wrong. I had typed it by hand
var VehiclesData = {
"VehiclesData": {
"VehiclesList": [
{ "year": "2010", "make": "honda", "model": "civic" },
{ "year": "2011", "make": "toyota", "model": "corolla" },
{ "year": "2012", "make": "audi", "model": "a4" }]
}
}
I'm trying to send this to a .net Web Service API like this:
[WebMethod]
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
public string ProcessData(VehiclesData VehiclesData)
{
//...Do stuff here with VehiclesData
}
public class VehiclesData
{
public List<Vehicle> VehiclesList = new List<Vehicle>();
public class Vehicle
{
private string year = string.Empty;
private string make = string.Empty;
private string model = string.Empty;
public string Year { get { return this.year; } set { this.make = value; } }
public string Make { get { return this.make; } set { this.make = value; } }
public string Model { get { return this.model; } set { this.model = value; } }
}
}
I'm getting "Object does not match target type".
With flat JSON objects, I'm getting the data just fine, but with array of objects and a c# List, I'm a little lost.
Upvotes: 2
Views: 2893
Reputation: 312
I'll mark peinearydevelopment's answer as the correct one for this question. I ended up taking bit of different approach, but all in all very similar to what he said.
I did change the JSON to be one level less (Same as what peinearydevelopment said) so that it only has an array of the Vehicle object and then in the WebMethod I accepted a list of the Vehicle object type:
[WebMethod]
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
public string ProcessData(List<Vehicle> Vehicles)
{
//.. Do stuff here
}
This worked for me. Hope it helps someone else out
Upvotes: 1
Reputation: 11474
To work as is, I think your JSON object needs to look like this: ie:
var VehiclesData = {
"VehiclesList":
[
{ "Year": "2010", "Make": "honda", "Model": "civic" },
{ "Year": "2011", "Make": "toyota", "Model": "corolla" },
{ "Year": "2012", "Make": "audi", "Model": "a4" }
]
};
Alternatively, you should be able to use some attributes to help.
[DataContract]
public class VehiclesData
{
[DataMember(Name = "year")]
public string Year { get; set; }
.
.
.
}
This will allow you to maintain the lowercase names in your JSON object, but you will still need to remove the "VehiclesData":{ part because I think during serialization .NET will assume that is a property.
Upvotes: 2