I am using Newtonsoft's Json.NET to deserialize a JSON string:
var output = JsonConvert.DeserializeObject<dynamic>("{ 'foo': 'bar' }");
How can I check that output is empty? An example test case:
var output = JsonConvert.DeserializeObject<dynamic>("{ }");
Assert.IsNull(output); // fails
The object you get back from DeserializeObject is going to be a JObject, which has a Count property. This property tells you how many properties are on the object.
var output = JsonConvert.DeserializeObject<dynamic>("{ }");
if (((JObject)output).Count == 0)
{
// The object is empty
}
This won't tell you if a dynamic object is empty, but it will tell you if a deserialized JSON object is empty.
You can also check with following code:
var output = JsonConvert.DeserializeObject<dynamic>("{ }");
if (output as JObject == null)
{
}
That worked for me.
You can just have a string conversion and check if its equal to "{ }".
var output = JsonConvert.DeserializeObject<dynamic>("{ }");
if (output.ToString() =="{ }")
{
// The object is empty
}
Related
Given a JToken called distance with the following content
{ "232": { "travelDistance": 25.0 } }
I would like to read the field travelDistance from it. First I tried this
distance.TryGetPropertyValue("travelDistance", float.MaxValue)
but this returns the fallback value float.MaxValue. Then I tried to use a JSON path
distance.SelectToken("$.travelDistance")
but this returns null. These are my debugging results
How can I read the value of the property travelDistance?
With JObject you can read the field values
var jObj = JObject.Parse(jsonString);
var result = Convert.ToDecimal(jObj["232"]["travelDistance"]);
OR
var result1 = Convert.ToDecimal(jObj.SelectToken("232.travelDistance"));
OR
var result2 = Convert.ToDecimal(jObj.SelectToken("*.travelDistance"));
OR
var result3 = jObj.SelectTokens("*.travelDistance")
.Select(x => Convert.ToDecimal(x))?
.FirstOrDefault();
Is it possible to pass in an argument to a dynamic object, so it returns the object required at runtime?
var file = File.ReadAllText("file.json");
dynamic json = JsonConvert.DeserializeObject(file);
var value = GetValue("EnvironmentConfiguration.Environment");
private static string GetValue(string jsonKey) {
// pass jsonKey somehow here? Something like this...
return json.(jsonKey);
}
Is this even possible?
EDIT:
Json file:
{
"EnvironmentConfiguration":
{
"Environment": "local"
}
}
Assuming we want to get the value "local" from "EnvironmentConfiguration.Environment".
I would use JObject and the SelectToken method:
var jobject = JObject.Parse(file);
var value = jobject
.SelectToken("EnvironmentConfiguration.Environment")
.ToString();
You can get your property by using indexer:
return json[jsonKey];
You can use Json.NET as follows:
dynamic json = JObject.Parse("{number:5555, str:'myString', array: [1,2,3,4,5]}");
var value1 = json.number; // get number value -> 5555
var value2 = json.str; // get string value -> myString
var value3 = json.array.Count; // get array count value -> 5
How do I get a specific nested property from a JSON using JObject?
For example i want to get the uri:
{
"embed": {
"uri": "/presets/88930"
...
There's many ways to access the property you're interested in.
Here's one:
String jsonData = "{ 'embed': { 'uri': '/presets/88930'}}";
var jObject = Newtonsoft.Json.Linq.JObject.Parse(jsonData);
Console.WriteLine((string)jObject["embed"]["uri"]);
if your jObject looks like:
var j = JObject.Parse(#"{""embed"": { ""uri"": ""/presets/88930"" } }");
dynamics makes accessing the object pretty easy:
string value = ((dynamic)j).embed.uri.ToString();
I'm working with C#, trying to parse JSON to XML, but first i need to validate the JSON and then check if it have a root element, there is my problem.
Suppose I got these two JSON strings:
string jsonWithoutRoot = "{'name': 'Fran', 'roles':['Admin','Coder']}";
string jsonWithRoot = "{'person': {'name': 'Fran','roles':['Admin','Coder']}}";
I want to get TRUE if the string have a root element like jsonWithRoot and FALSE in the other case.
A JSON string has one root object by definition. You're simply trying to count whether this root object has only one element.
This is trivially done by parsing the JSON into a JObject and getting the element count:
var jObject = JObject.Parse(jsonString);
bool hasOneElement = jObject.Count == 1;
I have been recently using this method to check what you are looking for. It might be helpfull.
public static bool HasOneProperty(string json)
{
JObject jsonObj = JObject.Parse(json);
if (jsonObj.Count > 1)
{
return false;
}
return true;
}
I have following problem: I have a json file that looks like this
{
"Path": {
"FirstPath": "/1/2/text()"
}
}
If I parse this JSON-File with Newtonsoft like this
dynamic dyn = JObject.Parse(json);
or this
dynamic dyn = JsonConvert.DeserializeObject(json);
I get a dynamic object that needs to be used like this
dyn.Path.FirstPath.Value
How can I get rid of the Value stuff? All of my objects in the JSON end up being a string. I don't want to always write ".Value" at the end if it is not necessary.
I tested this using Newtonsoft 8.0.2 and it works fine.
dynamic dyn = JObject.Parse(json);
string value = dyn.Path.FirstPath;
Value should equal /1/2/text().