1

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Small addition: Each converted returns it's own type in SupportedTypes. Not both as shown in initial post

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.