I was trying to use data from JSON file in automation test. Because I found how to work with it, thanks of @jeroenh I left here the correct way. I hope, it will help to somebody.
-- JSON file (testDataCo.Json):
{
"DataCo": [
{
"url": "https://dodo.com",
"user": "[email protected]",
"password": "uawe",
}
]
}
-- Class with data determination to JSON file
sing System.Globalization;
using Newtonsoft.Json.Converters;
using System.IO;
using Newtonsoft.Json;
namespace DataFromJson
{
public partial class DataJson
{
[JsonProperty("DataCo")]
public DataCo[] DataCo { get; set; }
}
public partial class DataCo
{
[JsonProperty("url")]
public string Url { get; set; }
[JsonProperty("user")]
public string User { get; set; }
[JsonProperty("password")]
public string Password { get; set; }
}
public partial class DataJson
{
public static DataJson FromJson(string json) => JsonConvert.DeserializeObject<DataJson>(json, DataFromJson.Converter.Settings);
}
public static class Serialize
{
public static string ToJson(this DataJson self) => JsonConvert.SerializeObject(self, DataFromJson.Converter.Settings);
}
internal static class Converter
{
public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
DateParseHandling = DateParseHandling.None,
Converters = {
new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
},
};
}
}
-- Here you can use data from JSON in variables
public class UseJsonInVar
{
string filepath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "../../testDataCo.json");
StreamReader ddd = new StreamReader(filepath);
var json = ddd.ReadToEnd();
DataJson objectJson = JsonConvert.DeserializeObject<DataJson>(json);
url = objectJson.DataCo[0].Url;
user = objectJson.DataCo[0].User;
pass = objectJson.DataCo[0].Password;
}
You're reading the contents of your file into the variable json
, but after that your code doesn't seem to do anything with it. An instance of JsonData
is created, but the actual JSON data is never passed to it.
You'll need a library to deserialize the JSON data into an object. You're already using Json.NET which is a good one. With the library in your project references, you can do:
JsonData obj = JsonConvert.DeserializeObject<JsonData>(json);
string plant = obj.plant; // "plant goco"