I am new to Tests in Visual Studio , normally I always used proper test tool in order to validate the json file and its data
I am stuck how to validate JSON objects , data inside in the JSON File
through following code I am Reading the JSON file , further i would like to validate the JSON objects
here is my readJSON method which reads the file but now I would like to either check if it contains any given specific value let say I would like to check if it contains the "Details" and its value "XYZG" or not
I tried to convert JSON into ToString() and then user .count method but it gives me the value 0 in output so I removed that ToString() block from the code
JSON Data
{
"Details":"XYZG",
"City":"Tokyo",
"Id":"ATOOO",
"Name":"Johny"
}
read json method
public string ReadMyJsonFile(String FilePath)
{
string storeValue = "";
using (StreamReader readerobject = new StreamReader(FilePath))
{
string jsonString = readerobject.ReadToEnd();
}
return storeValue;
}
TestMethod
public async TaskTest()
{
var json = ReadMyJsonFile(@"FilePath/Test.json");
var testobject = JsonConvert.DeserializeObject<JObject>(json);
Console.WriteLine(testobject);
try
{
if (testobject.SelectTokens("$..Id").Any(t => t.Value<string>() == "$..Id"))
{
Console.WriteLine("\n \n value exist");
}
}
catch (Exception ex)
{
Console.WriteLine("error keyword");
}
}
´´´
I am kinda stuck with the validation part of my json data
you better print a json string, not a JObject
try
{
var json = ReadMyJsonFile(@"FilePath/Test.json");
if (!string.IsNullOrEmpty(json))
{
Console.WriteLine("json file exists \n");
Console.WriteLine(json);
}
else
{
Console.WriteLine("json file not exists \n");
return;
}
var testObject = JObject.Parse(json);
if (!string.IsNullOrEmpty((string)testObject["Id"]))
{
Console.WriteLine("\n Id value exists");
Console.WriteLine((string)testObject["Id"]);
}
else
Console.WriteLine("\n Id value doesnt exist");
}
catch (Exception ex)
{
Console.WriteLine("error "+ex.Message);
}