I am passing a simple JSON string from my C# client to my webservice . Following is the string I send
"{ \"name\":\"S1\" }"
At the service end I use the following code
class DataDC
{
public String attr { get; set; }
public String attrVal { get; set; }
}
JavaScriptSerializer json_serializer = new JavaScriptSerializer();
DataDC dc = (DataDC)json_serializer.DeserializeObject(str);
I get the following error
"Unable to cast object of type 'System.Collections.Generic.Dictionary`2[System.String,System.Object]' to type 'DataDC'."
Shouldn't it be like this to deserialize to your class:
JavaScriptSerializer json_serializer = new JavaScriptSerializer();
DataDC dc = json_serializer.Deserialize<DataDC>(str);
Another thing is that you don have Name parameter in your model class therefore nothing will be passed to it. Your JSON should be like this: "{ \"attr\":\"some value\",\"attrVal\":\"some value\" }"
Or change your model class:
class DataDC {
public String name{ get; set; }
}
Your Json string/object does not match any of the properties of DataDC
In order for this to work, you would at least need to have a property called name within the class. e.g.
public class DataDC
{
public string name { get; set; }
public string attr { get; set; }
public string attrVal { get; set; }
}
This way you might get one property matched up.
Going with your existing Class, you would need the following Json string;
"{ \"attr\":\"S1\", \"attrVal\":\"V1\" }"
Note: You can also use the following code to deserialize;
DataDC dc = json_serializer.Deserialize<DataDC>(str);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With