Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"}
}
like image 367
Nickmccomb Avatar asked Oct 20 '25 00:10

Nickmccomb


1 Answers

JSON or not, the error is self-describing. You can not instantiate an interface or abstract class. They are just blue-prints of what functionality or object structure they'd represent.

For example, you can not do this:

var something = new ISomething();

but, you can do this:

ISomething something = new Something();

All you need is just some concrete implementation of that interface. Something like:

public JsonReceived : IBalance
{
// rest of the implementation
}

Or that might already be provided by the third-party, check their SDK documentation.

like image 129
Yahya Avatar answered Oct 21 '25 13:10

Yahya



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!