gpt4 book ai didi

c# - 无法将类型为 'Newtonsoft.Json.Linq.JObject' 的对象转换为类型

转载 作者:可可西里 更新时间:2023-11-01 08:37:33 43 4
gpt4 key购买 nike

这段代码:

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/

43 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com