views:

557

answers:

1

Hi All,

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 this 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!

+1  A: 

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.

jvenema
This is a great elaboration of my original question.. do you have an answer? thanks!
bill
ok that makes sense and is easiest enough.. Once i've typed them how i deserialize the whole thing again?
bill
I'm not familiar with the JavaScriptSerializer, but I'm guessing: Foo foo = JavaScriptSerializer.Deserialize<Foo>(incomingJson);
jvenema
If this worked, please accept it as the answer...
jvenema
thanks this is essentially correct.
bill