Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

json.net

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?

like image 643
Tony Avatar asked Jul 28 '16 15:07

Tony


People also ask

What is Jsonconvert DeserializeObject?

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 .

What is JArray C#?

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.

What is a JValue?

Represents a value in JSON (string, integer, date, etc). Newtonsoft.Json.Linq.

What is JToken in C#?

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.


1 Answers

You need to specify the type when deserializing.

Either:

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

Or:

var myCommandMessage = (CommandMessage)JsonConvert.DeserializeObject(json, typeof(CommandMessage));
like image 83
Brian Rogers Avatar answered Oct 08 '22 11:10

Brian Rogers