当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - Unable to cast object of type 'Newtonsoft.Json.Linq.JObject' to type <MyClass>

问题描述:

This code:

var commandMessage = new CommandMessage { CorrelationId = Guid.NewGuid() };

var json = JsonConvert.SerializeObject(commandMessage);

var myCommandMessage = (CommandMessage)JsonConvert.DeserializeObject(json);

gives this error message:

Additional information: Unable to cast object of type 'Newtonsoft.Json.Linq.JObject' to type 'QueueConnectionStringTester.CommandMessage'

This is the CommandMessage class:

public class CommandMessage

{

public Guid CorrelationId { get; set; }

}

What am I missing here?

网友答案:

You need to specify the type when deserializing.

Either:

var myCommandMessage = JsonConvert.DeserializeObject<CommandMessage>(json);

Or:

var myCommandMessage = (CommandMessage)JsonConvert.DeserializeObject(json, typeof(CommandMessage));
网友答案:

You need to give the type. JsonConvert class does not know anything about your CommandMessage class

    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);
    }
分享给朋友:
您可能感兴趣的文章:
随机阅读: