martin pb
martin pb

Reputation: 105

Read & map data from Json file in c# test

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;
    }

Upvotes: 6

Views: 10808

Answers (3)

Nachiappan Kumarappan
Nachiappan Kumarappan

Reputation: 291

If you could make your json file embedded, consider using the package JsonSectionReader

This package provides excellent support of unit testing with data in json.

Upvotes: 0

jeroenh
jeroenh

Reputation: 26782

Your class has a root object, and the 'Dataco' field is an array.

You can easily convert json to the correct classes in Visual Studio using the 'Edit - Paste Special - Paste Json as Classes' function. Another possibility is using an online json-to-c# convertor, such as https://app.quicktype.io/#l=cs

public partial class RootData
{
    [JsonProperty("DataCo")]
    public DataCo[] DataCo { get; set; }
}

public partial class DataCo
{
    [JsonProperty("discount")]
    public long Discount { get; set; }

    [JsonProperty("quote name")]
    public string QuoteName { get; set; }

    [JsonProperty("base price")]
    public long BasePrice { get; set; }

    [JsonProperty("product description")]
    public string ProductDescription { get; set; }

    [JsonProperty("plant")]
    public string Plant { get; set; }

    [JsonProperty("url")]
    public string Url { get; set; }

    [JsonProperty("final price")]
    public long FinalPrice { get; set; }

    [JsonProperty("password")]
    public string Password { get; set; }

    [JsonProperty("quote id")]
    public string QuoteId { get; set; }

    [JsonProperty("freight")]
    public string Freight { get; set; }

    [JsonProperty("billing price")]
    public long BillingPrice { get; set; }

    [JsonProperty("quantity")]
    public long Quantity { get; set; }

    [JsonProperty("proposed price")]
    public long ProposedPrice { get; set; }

    [JsonProperty("user")]
    public string User { get; set; }

    [JsonProperty("product id")]
    public long ProductId { get; set; }
}

Given this class, you can deserialize the json text with Newtonsoft JSON.Net:

JsonConvert.DeserializeObject<RootData>(json);

Upvotes: 1

Alexander van Oostenrijk
Alexander van Oostenrijk

Reputation: 4754

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"

Upvotes: 3

Related Questions