-1

There's a lot of Qs on this, but I need a solution without JSON.Net, etc. - I must use the canned stuff in Asp.Net MVC.

How can I serialize a POCO with a dynamic property - and get all the static properties, too? What I found was the dynamic only, or the static type which is easy.

e.g.

public class ReturnThisClassAsJSON {
    public int Id {get; set; }
    public string Name { get; set; }
    public ContainedClass ContainedContents { get; set; }
}

public class ContainedClass {
    public int Order { get; set; }
    public string Label { get; set; }
    public dynamic DynamicInfo { get; set; }
    public List<dynamic> DynamicList { get; set }
}
Wagner DosAnjos
  • 6,304
  • 1
  • 15
  • 29
Trober
  • 259
  • 1
  • 2
  • 8
  • Can you provide a sample data and the expected serialized JSON output? – Wagner DosAnjos Jan 05 '17 at 23:34
  • 1
    What do you mean by _What I found was the dynamic only, or the static type which is easy._? Do you have some code that you tried and did not work? Can you share it? – Wagner DosAnjos Jan 05 '17 at 23:35
  • See http://stackoverflow.com/questions/5156664/how-to-flatten-an-expandoobject-returned-via-jsonresult-in-asp-net-mvc. A class with *both* dynamic and static types is what I'm trying to do. Any object hierarchy of static types is easy. Throw dynamics into the POCOs and still make it work. – Trober Jan 06 '17 at 00:11

1 Answers1

0

My own answer:

I replaced the dynamic from the DynamicInfo and DynamicList from the ContainedClass with static types.

With the dynamic, I had 1 of 2 choices. Either serialize the dynamic to a string in its own serialization call using above SO question 5156664. (Which left me with the rest of the class I also wanted serialized and merged with it, thus this question). Or, incur this error:

"A circular reference was detected while serializing an object of type 'System.Reflection .RuntimeModule' ".

when attempting a single serialization call on the ContainedClass.

So, I transferred the dynamics into static-typed classes:

public class ColumnValue 
{
    public string Name { get; set; }
    public string Value { get; set; }
}

public class DynamicRow 
{
    public List<ColumnValue> ColumnValue { get; set; }
}

and, change ContainedClass to this:

public class ContainedClass
{
    public List<ColumnValue> DynamicInfo { get; set; }
    public List<DynamicRow>  Data { get; set; }
}

And, it serializes using out-of-the-box Asp.Net MVC:

 return Json(ReturnThisClassAsJSON, JsonRequestBehaviour.AllowGet);
Trober
  • 259
  • 1
  • 2
  • 8