Newton.JSON convert dynamic object to JObject instead of dynamic object - c#

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

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;
...

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);

Related

How can i convert an array in Json string to c# object?

I have a json return result like the following:
Json =
{
"Id":"12345",
"FirstName":"Bob",
"LastName":"Builder",
"Links":[]
}
Links can have a list of objects of type LinkService, i want to cast even if the array is empty , so in c# i get an empty array.
I do the following
var token = JObject.Parse(Json);
var Id = token.Value<string>("Id");
var fname = token.Value<string>("FirstName");
var lbname = token.Value<bool>("LastName");
var links = JsonSerializer.Deserialize<List<LinkService>>(token.Value<Array>("Links"));
Issue is that it says cant convert System.Array to Newtonsoft.Json.JsonReader
You can convert the jToken to an object using the ToObject method:
var links = token["Links"].TObject<List<LinkService>>();

Dynamic variable not working in C# with Json.Net

Can anyone tell me why I get an error when trying to output"dJson2.Type" in the code below?
string Json1= #"[{'Id':1, 'FirstName':'John', 'LastName':'Smith'}, {'Id':2, 'FirstName':'Jane', 'LastName':'Doe'}]";
dynamic dJson1= JsonConvert.DeserializeObject(Json1);
Console.WriteLine(dJson1.GetType());
Console.WriteLine(dJson1.Type);
string Json2 = #"{'Id':1, 'FirstName':'John', 'LastName':'Smith'}";
dynamic dJson2 = JsonConvert.DeserializeObject(Json2);
Console.WriteLine(dJson2.GetType());
Console.WriteLine(dJson2.Type);
The program dies on the Console.WriteLine(dJson2.Type) statement. The output of the program is...
Newtonsoft.Json.Linq.JArray
Array
Newtonsoft.Json.Linq.JObject
(should say Object here, I think)
Inspecting the local variables, dJson2 has a "Type" property with value "Object".
This is because JObject behaves similarly as System.Dynamic.ExpandoObject. Try to change your example to:
string Json2 = #"{'Id':1, 'FirstName':'John', 'LastName':'Smith'}";
dynamic dJson2 = JsonConvert.DeserializeObject(Json2);
dJson2.Type = "mynewfield";
Console.WriteLine(dJson2.GetType());
Console.WriteLine(dJson2.Type);
If you want to get property of underlying type you need to cast it (to JToken or JObject), otherwise requested property will be searched in
IDictionary<string, JToken> that JObject implements.
This example may help:
dynamic oobj = new JObject();
oobj.Type = "TEST";
Console.WriteLine(oobj.Type);
Console.WriteLine(((JObject)oobj).Type);

Can't get value from JTOken

I have this JToken
var pv = JToken.Parse(keys["parameterValues"].ToString()).ToList()[0];
Which returns this value
{"DE:Actual Savings": 42217.0}
I can't use .Value because the float is represented as an object {42217.0}
How can I get this number? Right now I am using .ToString() and converting it
To convert the value to a defined type you could use one of the defined methods below:
System.Convert.ChangeType(jtoken.ToString(), targetType);
or
JsonConvert.DeserializeObject(jtoken.ToString(), targetType);
Let's take into consideration our sample:
string json = #{"DE:Actual Savings": 42217.0}
You could do something like:
var obj = (JObject)JsonConvert.DeserializeObject(json);
Type type = typeof(float);
var i1 = System.Convert.ChangeType(obj["DE:Actual Savings"].ToString(), type);
Hope this solves your problem.

Getting a specific field from a JSON string without deserializing in C#

I currently have a REST app which returns a JSON string something like:
[{error: "Account with that email exists"}]
For when an error is thrown. I don't want to deserialize it into a custom "error" object, because it seems a bit wasteful and pointless. Is there a simple way to just extract a specific field out of a JSON string without making a custom class to reflect it.
Thanks
You have a couple of options if you don't want to create a custom class, you can deserialize to dynamic:
dynamic tmp = JsonConvert.DeserializeObject(yourString);
string error = (string)tmp.error;
Or deserialize to a dictionary:
var dic = JsonConvert.DeserializeObject<Dictionary<string, string>>();
string error = dic["error"];
No need third party libraries. Use native JavaScriptSerializer.
string input = "[{error: \"Account with that email exists\"}]";
var jss = new JavaScriptSerializer();
var array = jss.Deserialize<object[]>(input);
var dict = array[0] as Dictionary<string, object>;
Console.WriteLine(dict["error"]);
// More short with dynamic
dynamic d = jss.DeserializeObject(input);
Console.WriteLine(d[0]["error"]);
Have a look at JObject.
dynamic obj = JObject.Parse("{ myerrors: [{error: \"Account with that email exists\"}] }");
var a = obj.myerrors[0];
string error = a.error;

JObject how to read values in the array?

This is the json string:
{"d":[{"numberOfRowsAdded":"26723"}]}
string json = DAO.getUploadDataSummary();
JObject uploadData = JObject.Parse(json);
string array = (string)uploadData.SelectToken("d");
How do I change the code to reader the values in 'numberOfRowsAdded?
JObject uploadData = JObject.Parse(json);
int rowsAdded = Convert.ToInt32((string)uploadData["d"][0]["numberOfRowsAdded"])
You need to cast to JArray:
string json = "{\"d\":[{\"numberOfRowsAdded\":\"26723\"}]}";
JObject parsed = JObject.Parse(json);
JArray array = (JArray) parsed["d"];
Console.WriteLine(array.Count);
You can cast your JObject as a dynamic object.
You can also cast your array to JArray object.
JObject yourObject;
//To access to the properties in "dot" notation use a dynamic object
dynamic obj = yourObject;
//Loop over the array
foreach (dynamic item in obj.d) {
var rows = (int)item.numberOfRowsAdded;
}
I played around with writing a generic method that can read any part of my json string. I tried a lot of the answers on this thread and it did not suit my need. So this is what I came up with. I use the following method in my service layer to read my configuration properties from the json string.
public T getValue<T>(string json,string jsonPropertyName)
{
var parsedResult= JObject.Parse(json);
return parsedResult.SelectToken(jsonPropertyName).ToObject<T>();
}
and this is how you would use it :
var result = service.getValue<List<string>>(json, "propertyName");
So you can use this to get specific properties within your json string and cast it to whatever you need it to be.

Categories