Reputation: 348
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.
Upvotes: 0
Views: 1807
Reputation: 309
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;
}
Upvotes: 1
Reputation: 151710
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;
Upvotes: 4