davidvera
davidvera

Reputation: 1489

c# Generate dynamic fields for model object

I have to return an object that contains n fields from an API call which i don't know the values and the keys.

for example the json response is :

{
    "1": 0.98
    "2": 0.77
    "3": 0.65
    "4": 0.42
    "5": 0.41
    ....
}

During the API call i want to map the response with an object: The method entry point is the following :

    static GetResult GetResult(string token, int id)
    {
        GetResult result = appService.GetResult(token, id);
        return result;
    } 

the method is calling a service layer :

    public GetResult GetResult(string token, int id)
    {
        GetResult returnValue = new GetResult();
        Uri uri = new Uri(Constants.baseUrl + "getResults/" + id);
        Task<GetResult> getResult = httpRequest.GetResult(token, uri);
        returnValue = getResult.GetAwaiter().GetResult();
        return returnValue;
    }

Finally the method that makes the call is the following:

    public async Task<GetResult> GetResult(string token, Uri url)
    {
        HttpClient client = new HttpClient(); 
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);

        var req = new HttpRequestMessage(HttpMethod.Get, url); 
        var response = await client.SendAsync(req); 
        
        string output = await response.Content.ReadAsStringAsync();
        Console.WriteLine(JsonConvert.DeserializeObject(output));
        GetResult returnValue = JsonConvert.DeserializeObject<GetResult>(output);
        
        return returnValue;
    }

the whole logic is working but i don't know how to create a flexible model that fits the fact that my response can have 5 fields in the response or 20 for example.

I would like to avoid such model (rather dirty and with static size)

public class GetResult
{
    [JsonProperty(PropertyName = "1")]
    public double Property1 { get; set; }
    
    [JsonProperty(PropertyName = "2")]
    public double Property2 { get; set; }

    ... 

    [JsonProperty(PropertyName = "20")]
    public double Property20 { get; set; }
}

thanks!

Upvotes: 0

Views: 58

Answers (1)

vernou
vernou

Reputation: 7590

Your result is only key/value, maybe you can consider to replace GetResult type by Dictionary<string, double> like :

public async Task<Dictionary<string, double>> GetResult(string token, Uri url)
{
    HttpClient client = new HttpClient(); 
    ...
    var returnValue = JsonConvert.DeserializeObject<Dictionary<string, double>>(output);
    return returnValue;
}

Upvotes: 1

Related Questions