gpt4 book ai didi

c# - WebAPI 在返回 JSON 而不是 XML 时正确序列化从抽象类型派生的类

转载 作者:行者123 更新时间:2023-11-30 21:43:05 24 4
gpt4 key购买 nike

我的模型:

    public abstract class BaseClass
{
public string id { get; set; }
}

[KnownType(typeof(BaseClass))]
public class ChildClass1 : BaseClass
{
public string shape { get; set; }
}

[KnownType(typeof(BaseClass))]
public class ChildClass2: BaseClass
{
public string color { get; set; }
}

public class Widget
{
public List<BaseClass> Contents { get; set; }
public Widget()
{
Contents = new List<BaseClass>();
}
}

我的网络 API 端点:

        [HttpGet]
public Widget Get()
{
Widget widget = new Widget();
ChildClass1 cc1 = new ChildClass1();
cc1.id = "1234";
cc1.shape = "round";
ChildClass2 cc2 = new ChildClass2();
cc2.id = "4321";
cc2.color = "red";
widget.Contents.Add(cc1);
widget.Contents.Add(cc2);
return widget;
}

当请求输出为 XML 时,它在序列化我的派生类时遇到问题。

The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'.

Type 'WebApplication1.Models.ChildClass1' with data contract name 'ChildClass1:http://schemas.datacontract.org/2004/07/WebApplication1.Models' is not expected. Consider using a DataContractResolver if you are using DataContractSerializer or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to the serializer.

最佳答案

您应该将 KnownType 属性添加到 Widget 类,并指定所有可能的类型,这些类型可以作为 Contents< 的 BaseClass 实例传递 列表:

[KnownType(typeof(ChildClass1))]
[KnownType(typeof(ChildClass2))]
public class Widget
{
public List<BaseClass> Contents { get; set; }
public Widget()
{
Contents = new List<BaseClass>();
}
}

序列化响应:

<Widget xmlns:i="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://schemas.datacontract.org/2004/07/YourNamespace">
<Contents>
<BaseClass i:type="ChildClass1">
<id>1234</id>
<shape>round</shape>
</BaseClass>
<BaseClass i:type="ChildClass2">
<id>4321</id>
<color>red</color>
</BaseClass>
</Contents>
</Widget>

关于c# - WebAPI 在返回 JSON 而不是 XML 时正确序列化从抽象类型派生的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42035359/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com