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

时间:2016-07-28 15:58:42

标签: c# json.net

此代码:

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

我在这里缺少什么?

2 个答案:

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