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

Time:12-22

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

CodePudding user response:

You need to parse the .json file to object. If you don't have some build in function for it, you can use some third party library. Some example is described HERE

May be you need to change structure of .json file to Dictionary or array

CodePudding user response:

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  
  • Related