JavaScriptSerializer deserialize object "collection" as property in object failing
Asked Answered
D

2

6

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!

Ditmore answered 2/6, 2010 at 16:27 Comment(0)
C
9

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.

Classis answered 2/6, 2010 at 16:33 Comment(3)
This is a great elaboration of my original question.. do you have an answer? thanks!Ditmore
ok that makes sense and is easiest enough.. Once i've typed them how i deserialize the whole thing again?Ditmore
I'm not familiar with the JavaScriptSerializer, but I'm guessing: Foo foo = JavaScriptSerializer.Deserialize<Foo>(incomingJson);Classis
K
0

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; }
}
Kloof answered 25/10, 2011 at 21:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.