Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
    }
like image 491
martin pb Avatar asked Aug 18 '18 13:08

martin pb


People also ask

How do you spell read past tense?

The past tense of read is read, spelt the same but pronounced differently. It is pronounced as red. The past participle of the verb read is the same as the past form read that is pronounced as red.

Is read or read?

Read is the past tense of read, it is pronounced in the same way as the word red. The present tense, read, is pronounced as reed, though it is spelled in the same manner as the past tense, read. Read means to have comprehended the symbols composing printed or written matter and interpreted them into information.

Have a read meaning?

"A read" is "a period of time spent reading". It means a half-hour or more, all at once, not a minute or two. He might read things 50 times a day, but they aren't part of this quiet period, when he does nothing but read, with no interruptions. That is "having a read".

What is the two meaning of read?

1a : to perform the act of reading words : read something. b(1) : to learn something by reading. (2) : to pursue a course of study. 2a : to yield a particular meaning or impression when read. b : to be readable or read in a particular manner or to a particular degree this book reads smoothly.


2 Answers

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"
like image 122
Alexander van Oostenrijk Avatar answered Oct 04 '22 22:10

Alexander van Oostenrijk


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);
like image 40
jeroenh Avatar answered Oct 04 '22 21:10

jeroenh