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?
DeserializeObject<T>(String,JsonConverter[]) Deserializes the JSON to the specified . NET type using a collection of JsonConverter. DeserializeObject(String, JsonSerializerSettings) Deserializes the JSON to a .
JArray(Object[]) Initializes a new instance of the JArray class with the specified content. JArray(JArray) Initializes a new instance of the JArray class from another JArray object.
Represents a value in JSON (string, integer, date, etc). Newtonsoft.Json.Linq.
JToken is the abstract base class of JObject , JArray , JProperty , and JValue , which represent pieces of JSON data after they have been parsed. JsonToken is an enum that is used by JsonReader and JsonWriter to indicate which type of token is being read or written.
You need to specify the type when deserializing.
Either:
var myCommandMessage = JsonConvert.DeserializeObject<CommandMessage>(json);
Or:
var myCommandMessage = (CommandMessage)JsonConvert.DeserializeObject(json, typeof(CommandMessage));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With