Reputation: 51937
I have a json custom converter using the standard asp.net library. My converter looks like this:
public class MyObjectToJson : JavaScriptConverter
public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
{
MyObject TheObject = obj as MyObject;
Dictionary<string, object> OutputJson = new Dictionary<string, object>();
OutputJson.Add("SomeProperty", TheObject.Property1);
//line that I'm not figuring out
//I have a type MyNestedObject nested in the object model of MyObject
//I added that nested converter in the SupportedTypes method
OutputJson.Add("TheNestedObject",....?);
return OutputJson;
}
public override IEnumerable<Type> SupportedTypes
{
get { return new Type[] { typeof(MyObject), typeof(MyNestedObject) }; }
}
Basically, I have another json custom converter that's called MyNestedObjectJson but I'm wondering where to plug it in.
Upvotes: 1
Views: 1118
Reputation: 51937
ok, I figured it out. I'm adding this answer for those who land on this page through google. It's really so super simple:
In the calling code, you register the converter of the nested object like this:
JavaScriptSerializer TheSerializer = new JavaScriptSerializer();
TheSerializer.RegisterConverters(new JavaScriptConverter[] {
new MyObjectToJson(), new MyNestedObjectToJson()
});
And then, in the json converter of the parent object, you simply write the line I had trouble with like this:
OutputJson.Add("TheNestedObject", TheObject.TheNestedObject);
Since the serializer has both converters registered, the converter of the nested object will kick in.
Hope this helps some.
Upvotes: 1