I have a js object structured like:
object.property1 = "some string";
object.property2 = "some string";
object.property3.property1 = "some string";
object.property3.property2 = "some string";
object.property3.property2 = "some string";
i'm using JSON.stringify(object) to pass this with ajax request. When i try to deserialize th开发者_Go百科is using JavaScriptSerializer.Deserialize as a Dictionary i get the following error:
No parameterless constructor defined for type of 'System.String'.
This exact same process is working for regular object with non "collection" properties.. thanks for any help!
It's because the deserializer doesn't know how to handle the sub-object. What you have in JS is this:
var x = {
'property1' : 'string',
'property2' : 'string',
'property3' : { p1: 'string', p2: 'string', p3: 'string' },
};
which doesn't have a map to something valid in C#:
HashTable h = new HashTable();
h.Add("property1", "string");
h.Add("property2", "string");
h.Add("property3", ???);
The ??? is because there's no type defined here, so how would the deserializer know what the anonymous object in your JS represents?
Edit
There is no way to do what you're trying to accomplish here. You'll need to make your object typed. For example, defining your class like this:
class Foo{
string property1 { get; set; }
string property2 { get; set; }
Bar property3 { get; set; } // "Bar" would describe your sub-object
}
class Bar{
string p1 { get; set; }
string p2 { get; set; }
string p3 { get; set; }
}
...or something to that effect.
As a more general answer, in my case I had objects that looked like:
{ "field1" : "value", "data" : { "foo" : "bar" } }
I originally had the data field as a string when it should've been a Dictionary<string, string>
as specified on MSDN for objects that use dictionary syntax.
public class Message
{
public string field1 { get; set; }
public Dictionary<string, string> data { get; set; }
}
精彩评论