Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to construct Object from JSON string

Tags:

json

c#

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'."

like image 586
sameer karjatkar Avatar asked Aug 09 '13 09:08

sameer karjatkar


2 Answers

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; }    
}
like image 133
Adam Moszczyński Avatar answered Oct 14 '22 20:10

Adam Moszczyński


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);
like image 38
Tim B James Avatar answered Oct 14 '22 20:10

Tim B James