I am trying to serialize a .net object contains another data contract object as a parameter. The code is as follows…
[DataContract]
public class JsonObject2
{
[DataMember(Name = "field1")]
string field1 { get; set; }
[DataMember(Name = "field2")]
string field2 { get; set; }
[DataMember(Name = "field3")]
object[][] test = { new object[]{"key1", "value1"}, new object[]{"key2", "value2"}, new object[]{"key3", "value3"} };
}
[DataContract]
public class JsonObject3
{
[DataMember(Name = "field1")]
public string field1 { get; set; }
[DataMember(Name = "field2")]
public object field2 { get; set; }
}
DataContractJsonSerializer dcjs2 = new DataContractJsonSerializer(typeof(JsonObject3));
JsonObject3 obj3 = new JsonObject3();
obj3.field1 = "hello";
obj3.field2 = new JsonObject2();
dcjs2.WriteObject(s, obj3);
s.Position = 0;
MessageBox.Show(new StreamReader(s).ReadToEnd());
Doing the above, results in the following exception…
“{“Type ‘JSONParser.Form1+JsonObject2’ with data contract name ‘Form1.JsonObject2:http://schemas.datacontract.org/2004/07/JSONParser’ is not expected. Add any types not known statically to the list of known types – for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer.”}”
I can’t figure out how to carry out any of the recommendations given in that exception.
- How do you add to the list of KnownTypes ?
- How do you use the KnownTypeAttribute ?
Ok, figured out how to do it. I didn’t want to delete this question in case someone else finds it useful, so here is the solution…
Notice the
[KnownType(typeof(JsonObject2))]above the declaration of the JsonObject2 class ? That solved it.