Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cast a Newton.Json deserialized generic object to a custom object? [closed]

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'
like image 301
SamJolly Avatar asked Aug 22 '14 16:08

SamJolly


People also ask

How do I deserialize JSON to an object?

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.

Does JsonConvert DeserializeObject throw exception?

Serialization or deserialization errors will typically result in a JsonSerializationException .

How does JsonConvert DeserializeObject work?

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.

How do you deserialize a JSON object in Python?

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.


2 Answers

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);
like image 117
Greg Burghardt Avatar answered Sep 28 '22 19:09

Greg Burghardt


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>();
like image 39
Sam Harwell Avatar answered Sep 28 '22 20:09

Sam Harwell