7

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

2
  • you should name your class properties like the one in json Commented Aug 9, 2013 at 10:01
  • 1
    how is your json deserializer supposed to know about the DataDC object nad how to map it? Commented Aug 9, 2013 at 10:01

3 Answers 3

28

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; }    
}
Sign up to request clarification or add additional context in comments.

1 Comment

@sameer could you please mention which of the two suggestions helped you (or both)?
2

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);

Comments

0

The reason you can't deserialize it is because it doesn't look at all like your class. You should create a class like this:

public class DataDC
{
    public string name{get; set;}
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.