C# 如何设置 JsonProperty 多个名称


 [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"
    }
}}

相关内容

  • 没有找到相关文章

最新更新