问题描述:

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);
    }
相关阅读:
Top