JObject how to read values in the array? - c#

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.

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

How to deserialize json where type of properties not fixed - can be empty string or an object, please suggest. how to handle this situation?

I have to process the JSON object returned by an API response.
I tried by creating expando object and than adding all the properties to it.
and than copying the value to it.
dynamic dPropertyLinkValue = new ExpandoObject();
dPropertyLinkValue.link = "";
dPropertyLinkValue.value = "";
I am expecting a better way to do this, without expando object.
You can deserialize JSON by casting it to dynamic object. Please refer below sample:
Here deserializing Json to dynamic object and after that loop through its properties and in that you can check you value that whether it is object or not.
string jsonText = "{a:'testString',b:{'prop1':'value1'}}";
var jObj = JsonConvert.DeserializeObject<dynamic>(jsonText);
foreach (JProperty property in jObj)
{
string text = property.Name + " : " + property.Value;
//Here you can check whether property.Value is Jobject or any other value
}

Elegant way to access first child using JSON.NET

I'm a bit confused with the Newtonsoft.Json JObject interface. Say I need to access the 'foo' property of the first child in my JSON object. My C# code:
string json = #"{
'someUnknownKey': { 'foo': 'bar' }
}";
JObject o = JObject.Parse(json);
JObject child = o.First.ToObject<JProperty>().Value.ToObject<JObject>();
string s = child["foo"].ToObject<string>();
This works, but is there a more elegant way to do it, without all the JProperty/JObject conversions?
EDIT: I would like to stress that the key name someUnknownKey is unknown so I can't use it in my code.
I believe you do need a conversion to indicate that you expect the first child token to be a property, but you can do it more simply than your current code:
string json = #"{
'someUnknownKey': { 'foo': 'bar' }
}";
JObject root = JObject.Parse(json);
Console.WriteLine(((JProperty) root.First).Value["foo"]);
Or to break it down slightly more clearly:
JObject root = JObject.Parse(json);
JProperty property = (JProperty) root.First;
Console.WriteLine(property.Value["foo"]);
Another option is to use the Properties() method to ask for the first property instead of the first child token. That way you don't need any conversion.
JObject root = JObject.Parse(json);
Console.WriteLine(root.Properties().First().Value["foo"]);
You can do something like this.
var jtk = o.Descendants().First().Children().First().Value<string>("foo")
You can query the json object as dynamic:
string json = #"{
'someUnknownKey': { 'foo': 'bar' }
}";
dynamic o = JArray.Parse(json);
string child = o.someUnknownKey.foo;
Look here for a reference https://www.newtonsoft.com/json/help/html/QueryJsonDynamic.htm
Alternatively you can use [] to access json properties:
JObject o = JObject.Parse(json);
string value = (string)(o['someUnknownKey']['foo']);

Newtonsoft's JObject: read any property using a string expression

I have a JObject and want to get any property or array element coming from a string expression.
I already know how to do it explicitly, like:
jObject["a"][0]["b");
But I would like to do something like: jObject("a[0].b");
The reason is that I am allowing the user to specify what to gather from the JSON object, rather than hardcoding the operation.
You can use SelectToken
string json = #"{a:[{b:1}]}";
var jobj = JObject.Parse(json);
var token = jobj.SelectToken("a[0].b");
Console.WriteLine(token);

Newton.JSON convert dynamic object to JObject instead of dynamic object

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

Categories