I am trying to find the count of the total nodes inside a file which is in JSON format. I tried the below code and it is not working. Googled few but couldn't find what I am looking for. I am new to JSON file handling, please guide me.
Json Input 1:
{
"CandidateId": "E3",
"Ngocentre": "Chennai",
"FirstName": "XXX",
"LastName": "YYY",
"PhoneNumber": 22221,
"EmailId": "[email protected]",
"EducationalQualification": "Graduate",
"SkillSet": "ASP.NET",
"CreatedByNgo": "Gurukul",
"UpdatedByNgo": "Gurukul",
"CreatedDate": "0001-01-01T00:00:00",
"ModifiedDate": "0001-01-01T00:00:00",
"NgoemailId": "[email protected]"
}
** Json Input 2:**
[
{
"CandidateId": "E3",
"Ngocentre": "Chennai",
"FirstName": "XXX",
"LastName": "YYY",
"PhoneNumber": 22221,
"EmailId": "[email protected]",
"EducationalQualification": "Graduate",
"SkillSet": "ASP.NET",
"CreatedByNgo": "Gurukul",
"UpdatedByNgo": "Gurukul",
"CreatedDate": "0001-01-01T00:00:00",
"ModifiedDate": "0001-01-01T00:00:00",
"NgoemailId": "[email protected]"
},
{
"CandidateId": "E3",
"Ngocentre": "Chennai",
"FirstName": "XXX",
"LastName": "YYY",
"PhoneNumber": 22221,
"EmailId": "[email protected]",
"EducationalQualification": "Graduate",
"SkillSet": "ASP.NET",
"CreatedByNgo": "Gurukul",
"UpdatedByNgo": "Gurukul",
"CreatedDate": "0001-01-01T00:00:00",
"ModifiedDate": "0001-01-01T00:00:00",
"NgoemailId": "[email protected]"
}
]
My ideal output should be "1" for the 1st input and "2" for the 2nd input. I tried the below code.
using (StreamReader r = new StreamReader(@"C:\Users\xxx\Desktop\Read.txt"))
{
string json = r.ReadToEnd();
dynamic source = JsonConvert.DeserializeObject(json);
int count = ((Newtonsoft.Json.Linq.JContainer)((Newtonsoft.Json.Linq.JToken)source).Root).Count;
}
But when pass only the 1st input, I am getting count as 13 which is the total properties inside a Json. Above code piece returns 2 for the 2nd input which is the ideal output, but it fails when I pass 1st input alone.
CodePudding user response:
you can just count the tokens :
if (json.StartsWith("["))
{
// If the json is an array
var array = JArray.Parse(json);
Console.WriteLine(array.Count);
}
else
{
// If the json is only one object, the result is 1.
// I added a way to retieve the object as token array :
var jobject = JObject.Parse(json);
var tokens = jobject.SelectTokens("$"); // You can go through you object : jobject.SelectTokens("$.CandidateId") => "E3"
Console.WriteLine(tokens.Count());
}
An other solution would be the Regex with atomic group.
CodePudding user response:
Parsing the array manually is overkill, you just need to parse a JArray
out of it.
using (StreamReader r = new StreamReader(@"C:\Users\xxx\Desktop\Read.txt"))
{
var array = JsonSerializer.CreateDefault().Deserialize<JArray>(r);
Console.WriteLine(array.Count);
}