I am using Newton's Json.Net to deserialize Json to a .NET object. I am trying to understand whether one can cast from a general object to a specific object.
ie:
object myObject JsonConvert.DeserializeObject<object>(myJsonValue);
myOrder = (Order)myObject;
The code is more about decribing my question. I understand that one could do this:
object myObject JsonConvert.DeserializeObject<order>(myJsonValue);
But due to the fact this is a helper function then it could not be "order", but something more general.
Thanks.
EDIT:
Getting the error:
Getting Unable to cast object of type 'Newtonsoft.Json.Linq.JObject' to type 'Order'
A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method.
Serialization or deserialization errors will typically result in a JsonSerializationException .
In Deserialization, it does the opposite of Serialization which means it converts JSON string to custom . Net object. In the following code, it calls the static method DeserializeObject() of the JsonConvert class by passing JSON data. It returns a custom object (BlogSites) from JSON data.
To deserialize the string to a class object, you need to write a custom method to construct the object. You can add a static method to ImageLabelCollection inside of which you construct Label objects from the loaded JSON dictionary and then assign them as a list to the class variable bbox.
I'm going to make an assumption here because the question isn't 100% clear, but I think I've got a good idea:
But due to the fact this is a helper function then it could not be "order", but something more general.
You need to add a type argument to your helper function:
public class SomeHelper
{
public T Deserialize<T>(string json)
{
return JsonConvert.DeserializeObject<T>(json);
}
}
And to use it:
SomeHelper helper = new SomeHelper();
string json = "...";
Order order = helper.Deserialize<Order>(json);
Rather than deserialize to an object
, it's easier to work with something deserialized to JToken
.
JToken myObject = JsonConvert.DeserializeObject<JToken>(myJsonValue);
You can then use the JToken.ToObject<T>()
method to perform the final conversion:
Order order = myObject.ToObject<Order>();
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