简体   繁体   中英

Convert List<objects> to a Dict <String, String> in C#

I want to create an app that shows me the value of a certain coin. I use KuCoin API. When I request pricing info, i get this response:

{
    "code": "200000",
    "data_fiat": {
        "LOKI": "0.39646657",
        "EXY": "0.01427250",
        "IOTX": "0.00411990",
        "MHC": "0.0035",
        "MXW": "0.14063173",
        ...
    }
}

I used Deserialze, and a Foreach loop to convert this to a List of data_fiat objects. Now, when I want to get a value I just type data_fiat.LOKI.

The problem is that I would need to create an IF for every possible coin (200+) and its ugly code. Is there a way to somehow convert this to a DICTIONARY, so I can use data_fiatDict[VAR]?

This is what I have now:

public static async Task<List<data_fiat>> GetPrices()
{
    FiatPrices data = new FiatPrices();
    List<data_fiat> price = new List<data_fiat>();

    string url = $"https://api.kucoin.com/api/v1/prices";
    using (HttpClient client = GetHttpClient())
    {
        try
        {
            string json = await client.GetStringAsync(url);
            data = JsonConvert.DeserializeObject<FiatPrices>(json);
            foreach (data_fiat item in data.price)
            {
                price.Add(item);
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    return price;
}

This returns a LIST of data_fiat

private async Task GenerateData(Coins Selection)
{
    Coindata.BindingContext = Selection;
    String CoinSelection = Selection.Name;
    pricelbl.Text = ??Dictionary??[CoinSelection];
}

So I need a dictionary or something like that to be in the??Dictionary?? spot.

If you declare the FiatPrices class with a dictionary, JsonConvert will automatically deserialize into this dictionary.

public class FiatPrices
{
    [JsonProperty("code")]
    public int Code { get; set; }

    [JsonProperty("data_fiat")]
    public Dictionary<string, decimal> Prices { get; set; }
}

Then you can deserialize and query with

FiatPrices data = JsonConvert.DeserializeObject<FiatPrices>(json);
decimal price = data.Prices["IOTX"];

If you only need the dictionary, you can extract it with a single assigment (no need to loop):

Dictionary<string, decimal> priceDict = data.Prices;

or in your GetPrices method with an adapted return type of Task<Dictionary<string, decimal>> :

return data.Prices;

You can make use of JObject and select the node you need, then deserialize it to Dictionary<string,string> .

so instead of doing this:

data = JsonConvert.DeserializeObject<FiatPrices>(json);
foreach (data_fiat item in data.price)
{
    price.Add(item);
}

you could do this:

JObject jObj = JObject.Parse(json);

var data_dictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(jObj["data_fiat"].ToString());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM