此代码:
var commandMessage = new CommandMessage { CorrelationId = Guid.NewGuid() };
var json = JsonConvert.SerializeObject(commandMessage);
var myCommandMessage = (CommandMessage)JsonConvert.DeserializeObject(json);
给出以下错误消息:
Additional information: Unable to cast object of type 'Newtonsoft.Json.Linq.JObject' to type 'QueueConnectionStringTester.CommandMessage'
这是CommandMessage类:
public class CommandMessage
{
public Guid CorrelationId { get; set; }
}
我在这里错过了什么?
反序列化时需要指定类型。
任一:
var myCommandMessage = JsonConvert.DeserializeObject<CommandMessage>(json);
或者:
var myCommandMessage = (CommandMessage)JsonConvert.DeserializeObject(json, typeof(CommandMessage));
您需要给出类型。JsonConvert类对CommandMessage类一无所知
public class CommandMessage
{
public Guid CorrelationId { get; set; }
}
static void Main(string[] args)
{
var commandMessage = new CommandMessage { CorrelationId = Guid.NewGuid() };
var json = JsonConvert.SerializeObject(commandMessage);
var myCommandMessage = JsonConvert.DeserializeObject<CommandMessage>(json);
}