Home > Enterprise >  Get JSON string by value
Get JSON string by value

Time:09-05

I have exchange rates for different currencies in my JSON file,

"exchangeRate":
            [
                {"baseCurrency":"UAH","currency":"CHF","saleRateNB":15.6389750,"purchaseRateNB":15.6389750,"saleRate":17.0000000,"purchaseRate":15.5000000},
                {"baseCurrency":"UAH","currency":"EUR","saleRateNB":18.7949200,"purchaseRateNB":18.7949200,"saleRate":20.0000000,"purchaseRate":19.2000000},
                {"baseCurrency":"UAH","currency":"GBP","saleRateNB":23.6324910,"purchaseRateNB":23.6324910,"saleRate":25.8000000,"purchaseRate":24.0000000},
                {"baseCurrency":"UAH","currency":"PLZ","saleRateNB":4.4922010,"purchaseRateNB":4.4922010,"saleRate":5.0000000,"purchaseRate":4.2000000},
                {"baseCurrency":"UAH","currency":"RUR","saleRateNB":0.3052700,"purchaseRateNB":0.3052700,"saleRate":0.3200000,"purchaseRate":0.2800000},
                {"baseCurrency":"UAH","currency":"SEK","saleRateNB":2.0283750,"purchaseRateNB":2.0283750},
                {"baseCurrency":"UAH","currency":"UAH","saleRateNB":1.0000000,"purchaseRateNB":1.0000000},
                {"baseCurrency":"UAH","currency":"USD","saleRateNB":15.0564130,"purchaseRateNB":15.0564130,"saleRate":15.7000000,"purchaseRate":15.3500000},
                {"baseCurrency":"UAH","currency":"XAU","saleRateNB":17747.7470000,"purchaseRateNB":17747.7470000},
                {"baseCurrency":"UAH","currency":"CAD","saleRateNB":13.2107400,"purchaseRateNB":13.2107400,"saleRate":15.0000000,"purchaseRate":13.0000000}
            ]

Those string have equal namings, how can I get one specific for USD for example? I mean, that I want to get whole string like {"baseCurrency":"UAH","currency":"USD","saleRateNB":15.0564130,"purchaseRateNB":15.0564130,"saleRate":15.7000000,"purchaseRate":15.3500000} if I am looking for USD. I used WebApi.Client, and the following approach which I found on MC

private static async Task ProcessExchangeRate()
    {
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/json"));

        var streamTask = client.GetStreamAsync("https://api.privatbank.ua/p24api/exchange_rates?json&date=01.12.2014");
        ExchangeRate rates = await JsonSerializer.DeserializeAsync<ExchangeRate>(await streamTask);
    }

It is filling this model

    [JsonPropertyName("date")]
    public string Date { get; set; }

    [JsonPropertyName("exchangeRate")]
    public object[] ExchangeRates { get; set; }

but I want to find a way to get only one string, not all at once.

CodePudding user response:

I would suggest just creating type hierarchy representing the needed properties and json structure and filtering after deserialization:

public class Root
{
    [JsonPropertyName("exchangeRate")]
    public List<ExchangeRate> ExchangeRate { get; set; }
}

// remove properties you don't need
public class ExchangeRate
{
    [JsonPropertyName("baseCurrency")]
    public string BaseCurrency { get; set; }

    [JsonPropertyName("currency")]
    public string Currency { get; set; }

    [JsonPropertyName("saleRateNB")]
    public double SaleRateNB { get; set; }

    [JsonPropertyName("purchaseRateNB")]
    public double PurchaseRateNB { get; set; }

    [JsonPropertyName("saleRate")]
    public double SaleRate { get; set; }

    [JsonPropertyName("purchaseRate")]
    public double PurchaseRate { get; set; }
}

var deserialized = JsonSerializer.Deserialize<Root>(myJsonResponse);
var rate = deserialized.ExchangeRate.FirstOrDefault(r => r.Currency == "USD");

CodePudding user response:

In this case you don't need any custom classes

var response = await client.GetAsync("https://api.privatbank.ua/p24api/exchange_rates?json&date=01.12.2014");
    
if (response.IsSuccessStatusCode)
{
    var json = await response.Content.ReadAsStringAsync();

    var exchangeRates = JsonNode.Parse(json)["exchangeRate"];
        
    var currency = "USD";
    var usd = exchangeRates.AsArray().Where(i=> (string) i["currency"] == currency).FirstOrDefault();
    var usdSaleRate = (decimal) usd["saleRate"];
   }

or using Newtonsoft.Json

        var exchangeRates = (JArray) JObject.Parse(json)["exchangeRate"];
        
        var currency = "USD";
        var usd = exchangeRates.Where(i=> (string) i["currency"] == currency).FirstOrDefault();
        var usdSaleRate = (decimal) usd["saleRate"]; //15.7
  • Related