Search code examples
c#restsharp

How to hold particular url key from .json file based on the value given in the function parameter


API Testing using RestSharp

I have added config.json file and maintaining all the URL in the file. Example

{
   "Url1": "http://localhost:45677",
   "Url2": "http://localhost:45897"
}

I would like to fetch particular URL from the config.json based on the given parameter added in class2

public class class2
{
    public void Url1_Request()
    {
        var client = class1.RestClient("Url1");
    }
    public void Url2_Request()
    {
        var client = class1.RestClient("Url2");
    }
}


public class class1
{
    public static RestClient RestClient(string url)
    {

        var client = new RestClient(url);
        return client;
    }
}


Solution

  • you can use this code

    using Newtonsoft.Json;
    .....
    
    public static RestClient restClient()
    {
        string json = string.Empty;
        using (StreamReader r = new StreamReader(@"C:\...\config.json"))
            json = r.ReadToEnd();
            
        var jsonObject=JObject.Parse(json);
        
        var url=GetUrl(jsonObject,"Url1");
       return new RestClient(url);
    }
        
    public string GetUrl(JObject jsonObject, string url)
    {
        return  (string) jsonObject[url];
    }
    

    url

    http://localhost:45677