[XmlElement("A", Type = typeof(MyModelA)), XmlElement("B", Type = typeof(MyModelB))]
public List<object> context{ get; set; }
可以工作,但是我想更改为JsonProperty,就像这样
[JsonProperty("A", ItemConverterType = typeof(MyModelA)), JsonProperty("B", ItemConverterType = typeof(MyModelB))]
public List<object> context{ get; set; }
失败了,我该怎么办?
{
node:{
A:{ MyModelA }
B:{ MyModelB }
}
}
最佳答案
您需要使用属性JsonExtensionData。尝试这个:
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)}
}
}
};
结果:
{
"Node": {
"A": {
"Foo": "Hello from Module A"
},
"B": {
"Boo": "Hello from Module B"
}
}}
关于c# - C#如何设置JsonProperty多个名称?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33363098/