gpt4 book ai didi

c# - 将具有基本类型的列表序列化为派生类型 json

转载 作者:行者123 更新时间:2023-11-30 17:12:31 25 4
gpt4 key购买 nike

我有一个 Web API Controller 操作,它有一个 CommandMessage 类型的参数。该类型有一个包含基本类型 CommandBase 的列表。我的问题是我无法将它们设为派生类型,在此示例中为 MyCommand。

我正在使用 JsonNetFormatter来自 Web API 贡献项目。它使用 Json.Net 作为序列化器。

网络 API Controller :

public class CommandController : ApiController
{
public HttpResponseMessage Post(CommandMessage command)
{
//command.Commands[0].GetType().Name is always "CommandBase" instead of "MyCommand"
var message = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(string.Format("Type of command 1 is '{0}'", command.Commands[0].GetType().FullName))
};
return message;
}
}

这是我的要求:

private void When()
{
using (client)
{
command = new MyCommand
{
CommandId = Guid.NewGuid(),
Id = Guid.NewGuid(),
Name = "Martin"
};

var message = new CommandMessage(Guid.NewGuid(),new List<CommandBase> {command});

var requestMessage = GetHttpRequestMessage(message);
var task = client.PostAsync("http://localhost.:16218/api/command", requestMessage.Content);
task.Wait();
responseMessage = task.Result;
}
}

private static HttpRequestMessage GetHttpRequestMessage<T>(T data)
{
var mediaType = new MediaTypeHeaderValue("application/json");
var jsonFormatter = new JsonNetFormatter(DefaultJsonSettings.Settings());

var requestMessage = new HttpRequestMessage<T>(data, mediaType, new[] {jsonFormatter});

return requestMessage;
}

作为 JSON:

{
"$type": "PostToBaseClassList.Models.CommandMessage, PostToBaseClassList",
"Commands": [
{
"$type": "PostToBaseClassList.Models.MyCommand, PostToBaseClassList",
"Id": "45923a41-0c15-46e3-907d-64dd06840539",
"Name": "Martin"
}
],
"MessageId": "c873970a-8621-4223-806e-b809039438ab"
}

API Controller 操作的返回消息是:

Type of command 1 is 'PostToBaseClassList.Models.CommandBase'

命令类:

 [DataContract]
[XmlRoot]
public class MyCommand : CommandBase
{
private readonly string name;

public MyCommand()
{
}

public MyCommand(Guid id, string name)
{
this.name = name;
Id = id;
}

[DataMember(Order = 1)]
[XmlElement]
public Guid Id { get; set; }

[DataMember(Order = 2)]
[XmlElement]
public string Name { get; set; }
}

[DataContract]
[KnownType("GetKnownTypes")]
public class CommandBase
{
public Guid CommandId { get; set; }

public static Type[] GetKnownTypes()
{
var query =
from type in typeof (CommandBase).Assembly.GetTypes()
where typeof (CommandBase).IsAssignableFrom(type)
select type;

var types = query.ToArray();
return types;
}
}

[DataContract]
[Serializable]
[XmlRoot]
public class CommandMessage
{
public CommandMessage()
{
}

public CommandMessage(Guid messageId, IEnumerable<CommandBase> commands)
{
MessageId = messageId;
Commands = new List<CommandBase>(commands);
}

[DataMember]
[XmlElement]
public List<CommandBase> Commands { get; set; }

[DataMember]
[XmlElement]
public Guid MessageId { get; set; }
}

Json.Net 设置:

//DefaultJsonSettings.Settings()
var settings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
TypeNameHandling = TypeNameHandling.Objects,
Converters = new List<JsonConverter>
{
new IsoDateTimeConverter
()
}
};

private static void RegisterFormatters(HttpConfiguration config)
{
var jsonNetFormatter = new JsonNetFormatter(DefaultJsonSettings.Settings());
config.Formatters.Insert(0, jsonNetFormatter);
}

有什么想法吗?

最佳答案

Json.NET 不遵守 KnownTypes 属性,您必须提供自己的转换器。

这个问题为这个问题提供了几种不同的解决方案: Using Json.NET converters to deserialize properties

关于c# - 将具有基本类型的列表序列化为派生类型 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10615089/

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