隐藏

无法将类型“Newtonsoft.Json.Linq.JObject”隐式转换为实体

发布:2021/6/24 13:50:49作者:管理员 来源:本站 浏览次数:1955

这段代码:
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));