无法将类型 'Newtonsoft.Json.Linq.JObject' 的对象强制转换为类型<MyClass>



此代码:

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);
    }

相关内容

  • 没有找到相关文章

最新更新