此代码:
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; }
}
我在这里缺少什么?
答案 0 :(得分:15)
您需要在反序列化时指定类型。
或者:
var myCommandMessage = JsonConvert.DeserializeObject<CommandMessage>(json);
或者:
var myCommandMessage = (CommandMessage)JsonConvert.DeserializeObject(json, typeof(CommandMessage));
答案 1 :(得分:2)
您需要提供类型。 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);
}