How can i convert JObject to object in C#?

Viewed 3125

I have a JObject such as :

JObject obj = new JObject();
obj.Add(new JProperty("Name","Olivier"));
obj.Add(new JProperty("Surname","Big"));
obj.Add(new JProperty("FatherName","Johnatan"));

I want to convert obj above to object

If I use the this code below

var result1 = Newtonsoft.Json.JsonConvert.DeserializeObject<object>(obj.ToString());

the result is like this Img1

But the result that wanted is like below

var TheResultIWant = new { Name = "Olivier", Surname = "Big", FatherName = "Johnatan" };

Img2

Is there any kind of way I can obtain the object like the second image. I cannot code like it because I don't know the property name.

2 Answers

Well, you could use method DeserializeAnonymousType for that:

    JObject obj = new JObject();
    obj.Add(new JProperty("Name", "Olivier"));
    obj.Add(new JProperty("Surname", "Big"));
    obj.Add(new JProperty("FatherName", "Johnatan"));

    var result = new
    {
        Name = "",
        Surname = "",
        FatherName = ""
    };
    result  = JsonConvert.DeserializeAnonymousType(obj.ToString(), result);

Another option is to use dynamic and third option which is by far most used is to create your own type and use it:

public class Person 
{
   public string Name { get; set; }
   ...
}

Person result = JsonConvert.DeserializeObject<Person>(obj.ToString());

A JObject is an already deserialized object. It can be used as a dynamic object so there's no need to serialize to a string and get back another object.

dynamic TheResultIWant = obj; 
var name=TheResultIWant.Name;

It's already possible to access properties by key, like a dictionary:

var name=obj["Name"];

This returns a JToken. If the type of the value is known, Value< T> or Values<T> can be used to retrieve it:

var name=obj["Name"].Value<string>();
Related