5
string  result ="{"AppointmentID":463236,"Message":"Successfully Appointment Booked","Success":true,"MessageCode":200,"isError":false,"Exception":null,"ReturnedValue":null}"

   dynamic d = JsonConvert.DeserializeObject<dynamic>(result);

d.GetType () is Newtonsoft.Json.Linq.JObject

so how to deserialize it to dynamic object instead of JObject

2 Answers 2

4

It's not quite clear what is not working for you and why you care about the return type but you could directly access the properties of the deserialized object like this:

string result = @"{""AppointmentID"":463236,""Message"":""Successfully Appointment Booked"",""Success"":true,""MessageCode"":200,""isError"":false,""Exception"":null,""ReturnedValue"":null}";
dynamic d = JsonConvert.DeserializeObject<dynamic>(result);

string message = d.Message;
int code = d.MessageCode;
...
Sign up to request clarification or add additional context in comments.

7 Comments

I cant access property directly because "d" is not dynamic object , but it is JObject so it will throw exception
"d" is not dynamic object: WRONG. d is a dynamic object because you declared it as dynamic and you can access any property you like. The JObject class has this nice property to automatically dispatch calls to its properties. Did you even try the code I have shown in my answer?
that is the first impression when you didn't actually tried the code , try to execute that code and you will get error on string message = d.Message; because "Message" does not exists, and that is my issue
you are right ,I executed the code outside of unit test and it worked, but inside unit test it converting it to JObject , that is weird
interesting, seems this happens whenever i deserialize a structured object which contains an array element, for example { "id": 1, "fail":["val1","val2"] }returns JObject and any late bound access results in a runtime binder exception
|
1

You probably want something like

var values = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(json);

This might also suit your needs (untested)

dynamic d = JsonConvert.DeserializeObject<ExpandoObject>(json);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.