3
 [XmlElement("A", Type = typeof(MyModelA)), XmlElement("B", Type = typeof(MyModelB))]
 public List<object> context{ get; set; }

Can work but I want change to JsonProperty ,like this

 [JsonProperty("A", ItemConverterType = typeof(MyModelA)), JsonProperty("B", ItemConverterType = typeof(MyModelB))]
 public List<object> context{ get; set; }

It failed ,How should I do?

{
  node:{
         A:{ MyModelA }
         B:{ MyModelB }
       }
}
Wesley Lomax
  • 2,067
  • 2
  • 20
  • 34
Kent
  • 31
  • 1
  • 4
  • Does that mean that, if you have multiple instances of `MyModelA` in the list, you want to see the property name `"A"` duplicated in the JSON object? The [JSON rfc](http://www.ietf.org/rfc/rfc4627.txt) says *The names within an object SHOULD be unique.* so I don't recommend it. – dbc Oct 27 '15 at 09:04
  • Have you considered using [`TypeNameHandling = TypeNameHandling.Auto`](http://www.newtonsoft.com/json/help/html/SerializeTypeNameHandling.htm) instead? – dbc Oct 27 '15 at 09:07
  • [Json.NET won't do that out of the box](http://www.newtonsoft.com/json/help/html/SerializationGuide.htm). It serializes non-dictionary collections to JSON arrays, not objects. Also, it doesn't particularly support duplicated property names in the same object, which you would seem to require. If you really need that, you might start with [How to deserialize JSON with duplicate property names in the same object](http://stackoverflow.com/questions/20714160). – dbc Oct 27 '15 at 18:49
  • Thanks for your answer,I know my problem ,so I try another way to make it work. – Kent Oct 28 '15 at 05:39

1 Answers1

0

You need to use attribute JsonExtensionData. Try this:

public sealed class ModuleA
{
    public string Foo { get; set; }
}
public sealed class ModuleB
{
    public string Boo { get; set; }
}
public class Node
{
    [JsonExtensionData]
    public Dictionary<string, JToken> Context { get; set; }
}
public class Example
{
    public Node Node { get; set; }
}

var moduleA = new ModuleA {Foo = "Hello from Module A"};
var moduleB = new ModuleB { Boo = "Hello from Module B" };
var example = new Example
        {
            Node = new Node
            {
                Context = new Dictionary<string, JToken>
                {
                    {"A", JToken.FromObject(moduleA)},
                    {"B", JToken.FromObject(moduleB)}
                }
            }
        };        

Result:

{
"Node": {
    "A": {
        "Foo": "Hello from Module A"
    },
    "B": {
        "Boo": "Hello from Module B"
    }
}}
  • That's not going to work when there are multiple instances of the same type; you'll get an `ArgumentException` trying to add a duplicate key to the dictionary. – dbc Oct 27 '15 at 18:44