Search code examples
c#jsonjson-deserialization

C# JSON Deserialization : Type is an interface or abstract class and cannot be instantiated


I'm using this C# project which uses APIs to communicate with the online trading platform Poloniex.

This code is supposed to get balances in a wallet:

var x = await polo_client.Wallet.GetBalancesAsync();

Although this code gives this error:

Error getting wallet:Could not create an instance of type Jojatekok.PoloniexAPI.WalletTools.IBalance.
Type is an interface or abstract class and cannot be instantiated.
Path '1CR.available', line 1, position 20.

in Helper.cs here:

[SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times")]
internal static T DeserializeObject<T>(this JsonSerializer serializer, string value)
{ 
    using (var stringReader = new StringReader(value))
    {
        using (var jsonTextReader = new JsonTextReader(stringReader))
        {
            return (T)serializer.Deserialize(jsonTextReader, typeof(T));
        }
    } 
}

The code to call this is:

public T GetData<T>(string command, params object[] parameters)
{
    var relativeUrl = CreateRelativeUrl(command, parameters);
    var jsonString = QueryString(relativeUrl);
    var output = JsonSerializer.DeserializeObject<T>(jsonString);
    return output;
}

Can someone tell me why I'm getting an error deserializing this JSON response?

The response is JSON, here is a sample of it:

{
"1CR":{"available":"0.00000000","onOrders":"0.00000000","btcValue":"0.00000000"},
"ABY":{"available":"0.00000000","onOrders":"0.00000000","btcValue":"0.00000000"}
}

Solution

  • This is what i have done to get it working. Thanks to Chris from Guru.com for getting this working. Great guy and very well priced. You can find him here: http://www.guru.com/freelancers/deatc

    private IDictionary<string, IBalance> GetBalances()
    {
        var postData = new Dictionary<string, object>();
        var data = PostData<IDictionary<string, Balance>>("returnCompleteBalances", postData);
        var returnData = new Dictionary<string, IBalance>();
    
        foreach (string key in data.Keys)
        {
            returnData.Add(key, data[key]);
        }
    
        return returnData;
    }