Home > Mobile >  Read json file from within sollution
Read json file from within sollution

Time:10-08

I want to create named httpclient for each serve definition existing in json file. But i have problem with it. I do not know how to access this json file

Json is defined like this in project:

enter image description here

This file just contains list of server names with their urls:

{
  "servers": [
    {
      "name": "first",
      "url": "firstUrl"
    },
    {
      "name": "second",
      "url": "secondUrl"
    }
  ]
}

Then in the main file i want to use it and created named httpclients for each of existing url :

builder.Services.AddHttpClient("Name", client =>
{
    client.BaseAddress = new Uri("Url");
    client.Timeout = new TimeSpan(0, 0, 30);
});

so later i could create specific httpclient depending on the params received:

public async Task<Players> GetPlayers(string serverName)
{
    var client = httpClientFactory.CreateClient(serverName);
    var list = await client.GetAsAsync<Players>("players.xml");
    return list;
}

CodePudding user response:

You can read the json file and deserialize it to the model. Then you can add HttpClient services to the service collection using this model.

Create your models according to your json structure;

public class TestModel
{
    public List<Server> Servers { get; set; }
}

public class Server
{
    public string Name { get; set; }
    public string Url { get; set; }    
}

Add services;

var jsonContent = File.ReadAllText("yourfilepath", Encoding.UTF8);

var json = JsonConvert.DeserializeObject<TestModel>(jsonContent);

foreach (var server in json.Servers)
{
    builder.Services.AddHttpClient(server.Name, client =>
    {
        client.BaseAddress = new Uri(server.Url);
        client.Timeout = new TimeSpan(0, 0, 30);
    });
}

That should work.

If you want read json easily from your entire application, you can use my open-source library.

CodePudding user response:

You can add any json file to the builder's Configuration, and read its data.

public class ServerModel
{
    public string Name { get; set; }
    public string Url { get; set; }
}
builder.Configuration.AddJsonFile("ServerList/servers.json");
IEnumerable<ServerModel> servers = builder.Configuration.GetSection("servers").Get<IEnumerable<ServerModel>>();

foreach(var server in servers)
{
    builder.Services.AddHttpClient(server.Name, client =>
    {
        client.BaseAddress = new Uri(server.Url);
        client.Timeout = new TimeSpan(0, 0, 30);
    });
}
  • Related