此代码:
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));
关于c# - 无法将类型为'Newtonsoft.Json.Linq.JObject'的对象强制转换为<MyClass>,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38641365/